diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 023be973..f0446091 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -160,7 +160,17 @@ pub enum SocketMessage { ToggleWorkspaceLayer, // TODO: look into maximized windows // ToggleMaximize, + CycleFocusMonitor(CycleDirection), + CycleFocusWorkspace(CycleDirection), + CycleFocusEmptyWorkspace(CycleDirection), + FocusMonitorNumber(usize), + FocusMonitorAtCursor, + FocusLastWorkspace, + CloseWorkspace, FocusWorkspaceNumber(usize), + FocusWorkspaceNumbers(usize), + FocusMonitorWorkspaceNumber(usize, usize), + FocusNamedWorkspace(String), MoveContainerToWorkspaceNumber(usize), SendContainerToWorkspaceNumber(usize), ResizeWindowEdge(OperationDirection, Sizing), diff --git a/komorebi/src/core_graphics/mod.rs b/komorebi/src/core_graphics/mod.rs index 34503769..b7758e4c 100644 --- a/komorebi/src/core_graphics/mod.rs +++ b/komorebi/src/core_graphics/mod.rs @@ -83,6 +83,30 @@ impl CoreGraphicsApi { .map(|display| CoreGraphicsApi::display_bounds(*display)) } + pub fn display_with_point(point: CGPoint) -> Option { + let mut displays: Vec = Vec::with_capacity(1); + let mut display_count = 0; + + unsafe { + match CoreGraphicsError::from(CGGetDisplaysWithPoint( + point, + displays.capacity() as u32, + displays.as_mut_ptr(), + &mut display_count, + )) { + CoreGraphicsError::Success => { + displays.set_len(display_count as usize); + } + error => { + tracing::error!("failed to find display for point: {error}"); + return None; + } + } + } + + displays.first().copied() + } + pub fn window_list_info() -> Option> { unsafe { CGWindowListCopyWindowInfo( diff --git a/komorebi/src/macos_api.rs b/komorebi/src/macos_api.rs index f47604bf..f6e70e79 100644 --- a/komorebi/src/macos_api.rs +++ b/komorebi/src/macos_api.rs @@ -15,6 +15,7 @@ use crate::monitor::Monitor; use crate::window::WindowInfo; use crate::window_manager::WindowManager; use objc2::MainThreadMarker; +use objc2_app_kit::NSEvent; use objc2_app_kit::NSScreen; use objc2_application_services::AXUIElement; use objc2_application_services::AXValue; @@ -22,6 +23,7 @@ use objc2_application_services::AXValueType; use objc2_core_foundation::CFDictionary; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFString; +use objc2_core_foundation::CGPoint; use objc2_core_foundation::CGRect; use std::collections::HashMap; use std::ffi::c_void; @@ -201,4 +203,15 @@ impl MacosApi { AccessibilityApi::copy_attribute_value::(&app, kAXFocusedWindowAttribute) } } + + pub fn cursor_pos() -> CGPoint { + unsafe { + let point = NSEvent::mouseLocation(); + CGPoint::new(point.x, point.y) + } + } + + pub fn monitor_from_point(point: CGPoint) -> Option { + CoreGraphicsApi::display_with_point(point) + } } diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index c9edaf9f..4b9bf8ca 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -8,9 +8,11 @@ use crate::macos_api::MacosApi; use crate::window_manager::WindowManager; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; +use color_eyre::eyre::eyre; use parking_lot::Mutex; use std::io::BufRead; use std::io::BufReader; +use std::num::NonZeroUsize; use std::os::unix::net::UnixStream; use std::str::FromStr; use std::sync::Arc; @@ -112,11 +114,232 @@ impl WindowManager { self.is_paused = !self.is_paused; } + SocketMessage::CycleFocusMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_else(|| eyre!("there must be at least one monitor"))?, + ); + + self.focus_monitor(monitor_idx)?; + self.update_focused_workspace(self.mouse_follows_focus, true)?; + } + SocketMessage::CycleFocusWorkspace(direction) => { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + + let focused_monitor = self + .focused_monitor() + .ok_or_else(|| eyre!("there is no monitor"))?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_else(|| eyre!("there must be at least one workspace"))?, + ); + + self.focus_workspace(workspace_idx)?; + } + SocketMessage::CycleFocusEmptyWorkspace(direction) => { + // TODO: figure out if we need to do this on macOS + // // This is to ensure that even on an empty workspace on a secondary monitor, the + // // secondary monitor where the cursor is focused will be used as the target for + // // the workspace switch op + // if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + // if monitor_idx != self.focused_monitor_idx() { + // if let Some(monitor) = self.monitors().get(monitor_idx) { + // if let Some(workspace) = monitor.focused_workspace() { + // if workspace.is_empty() { + // self.focus_monitor(monitor_idx)?; + // } + // } + // } + // } + // } + + let focused_monitor = self + .focused_monitor() + .ok_or_else(|| eyre!("there is no monitor"))?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let mut empty_workspaces = vec![]; + + for (idx, w) in focused_monitor.workspaces().iter().enumerate() { + if w.is_empty() { + empty_workspaces.push(idx); + } + } + + if !empty_workspaces.is_empty() { + let mut workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_else(|| eyre!("there must be at least one workspace"))?, + ); + + while !empty_workspaces.contains(&workspace_idx) { + workspace_idx = direction.next_idx( + workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_else(|| eyre!("there must be at least one workspace"))?, + ); + } + + self.focus_workspace(workspace_idx)?; + } + } + SocketMessage::FocusMonitorNumber(monitor_idx) => { + self.focus_monitor(monitor_idx)?; + self.update_focused_workspace(self.mouse_follows_focus, true)?; + } + SocketMessage::FocusMonitorAtCursor => { + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + self.focus_monitor(monitor_idx)?; + } + } + SocketMessage::FocusLastWorkspace => { + // TODO: figure out if we need to do this on macOS + // // This is to ensure that even on an empty workspace on a secondary monitor, the + // // secondary monitor where the cursor is focused will be used as the target for + // // the workspace switch op + // if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + // if monitor_idx != self.focused_monitor_idx() { + // if let Some(monitor) = self.monitors().get(monitor_idx) { + // if let Some(workspace) = monitor.focused_workspace() { + // if workspace.is_empty() { + // self.focus_monitor(monitor_idx)?; + // } + // } + // } + // } + // } + + let idx = self + .focused_monitor() + .ok_or_else(|| eyre!("there is no monitor"))? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.focus_workspace(last_focused_workspace)?; + } + + self.focused_monitor_mut() + .ok_or_else(|| eyre!("there is no monitor"))? + .last_focused_workspace = Option::from(idx); + } SocketMessage::FocusWorkspaceNumber(workspace_idx) => { if self.focused_workspace_idx().unwrap_or_default() != workspace_idx { self.focus_workspace(workspace_idx)?; } } + SocketMessage::FocusWorkspaceNumbers(workspace_idx) => { + // TODO: figure out if we need to do this on macOS + // // This is to ensure that even on an empty workspace on a secondary monitor, the + // // secondary monitor where the cursor is focused will be used as the target for + // // the workspace switch op + // if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + // if monitor_idx != self.focused_monitor_idx() { + // if let Some(monitor) = self.monitors().get(monitor_idx) { + // if let Some(workspace) = monitor.focused_workspace() { + // if workspace.is_empty() { + // self.focus_monitor(monitor_idx)?; + // } + // } + // } + // } + // } + + let focused_monitor_idx = self.focused_monitor_idx(); + + for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { + if i != focused_monitor_idx { + monitor.focus_workspace(workspace_idx)?; + monitor.load_focused_workspace(false)?; + } + } + + self.focus_workspace(workspace_idx)?; + } + SocketMessage::FocusMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { + let focused_monitor_idx = self.focused_monitor_idx(); + let focused_workspace_idx = self.focused_workspace_idx().unwrap_or_default(); + + let focused_pair = (focused_monitor_idx, focused_workspace_idx); + + if focused_pair != (monitor_idx, workspace_idx) { + self.focus_monitor(monitor_idx)?; + self.focus_workspace(workspace_idx)?; + } + } + SocketMessage::FocusNamedWorkspace(ref name) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(name) + { + self.focus_monitor(monitor_idx)?; + self.focus_workspace(workspace_idx)?; + } + } + SocketMessage::CloseWorkspace => { + // TODO: figure out if we need to do this on macOS + // // This is to ensure that even on an empty workspace on a secondary monitor, the + // // secondary monitor where the cursor is focused will be used as the target for + // // the workspace switch op + // if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + // if monitor_idx != self.focused_monitor_idx() { + // if let Some(monitor) = self.monitors().get(monitor_idx) { + // if let Some(workspace) = monitor.focused_workspace() { + // if workspace.is_empty() { + // self.focus_monitor(monitor_idx)?; + // } + // } + // } + // } + // } + + let mut can_close = false; + + if let Some(monitor) = self.focused_monitor_mut() { + let focused_workspace_idx = monitor.focused_workspace_idx(); + let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); + + if let Some(workspace) = monitor.focused_workspace() + && monitor.workspaces().len() > 1 + && workspace.containers().is_empty() + && workspace.floating_windows().is_empty() + && workspace.monocle_container.is_none() + && workspace.maximized_window.is_none() + && workspace.name.is_none() + { + can_close = true; + } + + if can_close + && monitor + .workspaces_mut() + .remove(focused_workspace_idx) + .is_some() + { + self.focus_workspace(next_focused_workspace_idx)?; + } + } + } + SocketMessage::MoveContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, true, None)?; } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 7e7981ed..6fb77722 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1303,4 +1303,45 @@ impl WindowManager { None } + + pub fn monitor_idx_from_current_pos(&mut self) -> Option { + let monitor_id = MacosApi::monitor_from_point(MacosApi::cursor_pos())?; + + for (i, monitor) in self.monitors().iter().enumerate() { + if monitor.id == monitor_id { + return Option::from(i); + } + } + + // TODO: figure out if we need this on macOS + // // our hmonitor might be stale, so if we didn't return above, try querying via the latest + // // info taken from win32_display_data and update our hmonitor while we're at it + // if let Ok(latest) = MacosApi::monitor(monitor_id) { + // for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { + // if monitor.device_id() == latest.device_id() { + // monitor.set_id(latest.id()); + // return Option::from(i); + // } + // } + // } + + None + } + + #[tracing::instrument(skip(self))] + pub fn monitor_workspace_index_by_name(&mut self, name: &str) -> Option<(usize, usize)> { + tracing::info!("looking up workspace by name"); + + for (monitor_idx, monitor) in self.monitors().iter().enumerate() { + for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { + if let Some(workspace_name) = &workspace.name + && workspace_name == name + { + return Option::from((monitor_idx, workspace_idx)); + } + } + } + + None + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 099eecd8..9138b880 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -21,6 +21,7 @@ use std::num::NonZeroUsize; #[derive(Debug, Clone)] pub struct Workspace { + pub name: Option, pub containers: Ring, pub monocle_container: Option, pub monocle_container_restore_idx: Option, @@ -68,6 +69,7 @@ impl_ring_elements!(Workspace, Window, "floating_window"); impl Default for Workspace { fn default() -> Self { Self { + name: None, containers: Default::default(), monocle_container: None, monocle_container_restore_idx: None, diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 5dc65108..ca37b104 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -62,6 +62,9 @@ gen_enum_subcommand_args! { Stack: OperationDirection, CycleStack: CycleDirection, PromoteWindow: OperationDirection, + CycleMonitor: CycleDirection, + CycleWorkspace: CycleDirection, + CycleEmptyWorkspace: CycleDirection, } macro_rules! gen_target_subcommand_args { @@ -78,9 +81,30 @@ macro_rules! gen_target_subcommand_args { } gen_target_subcommand_args! { - FocusWorkspace, + MoveToMonitor, MoveToWorkspace, - SendToWorkspace + SendToMonitor, + SendToWorkspace, + FocusMonitor, + FocusWorkspace, + FocusWorkspaces, +} + +macro_rules! gen_named_target_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + /// Target workspace name + workspace: String, + } + )+ + }; +} + +gen_named_target_subcommand_args! { + FocusNamedWorkspace, } #[derive(Parser)] @@ -99,6 +123,14 @@ struct ResizeAxis { sizing: Sizing, } +#[derive(Parser)] +struct FocusMonitorWorkspace { + /// Target monitor index (zero-indexed) + target_monitor: usize, + /// Workspace index on the target monitor (zero-indexed) + target_workspace: usize, +} + #[derive(Parser)] #[clap(author, about, version)] struct Opts { @@ -152,9 +184,36 @@ enum SubCommand { PromoteFocus, /// Promote the window in the specified direction PromoteWindow(PromoteWindow), + /// Focus the specified monitor + #[clap(arg_required_else_help = true)] + FocusMonitor(FocusMonitor), + /// Focus the monitor at the current cursor location + FocusMonitorAtCursor, + /// Focus the last focused workspace on the focused monitor + FocusLastWorkspace, /// Focus the specified workspace on the focused monitor #[clap(arg_required_else_help = true)] FocusWorkspace(FocusWorkspace), + /// Focus the specified workspace on all monitors + #[clap(arg_required_else_help = true)] + FocusWorkspaces(FocusWorkspaces), + /// Focus the specified workspace on the target monitor + #[clap(arg_required_else_help = true)] + FocusMonitorWorkspace(FocusMonitorWorkspace), + /// Focus the specified workspace + #[clap(arg_required_else_help = true)] + FocusNamedWorkspace(FocusNamedWorkspace), + /// Close the focused workspace (must be empty and unnamed) + CloseWorkspace, + /// Focus the monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMonitor(CycleMonitor), + /// Focus the workspace in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleWorkspace(CycleWorkspace), + /// Focus the next empty workspace in the given cycle direction (if one exists) + #[clap(arg_required_else_help = true)] + CycleEmptyWorkspace(CycleEmptyWorkspace), /// Move the focused window to the specified workspace #[clap(arg_required_else_help = true)] MoveToWorkspace(MoveToWorkspace), @@ -276,6 +335,41 @@ fn main() -> eyre::Result<()> { SubCommand::ToggleCrossMonitorMoveBehaviour => { send_message(&SocketMessage::ToggleCrossMonitorMoveBehaviour)?; } + SubCommand::FocusMonitor(arg) => { + send_message(&SocketMessage::FocusMonitorNumber(arg.target))?; + } + SubCommand::FocusMonitorAtCursor => { + send_message(&SocketMessage::FocusMonitorAtCursor)?; + } + SubCommand::FocusLastWorkspace => { + send_message(&SocketMessage::FocusLastWorkspace)?; + } + SubCommand::FocusWorkspaces(arg) => { + send_message(&SocketMessage::FocusWorkspaceNumbers(arg.target))?; + } + SubCommand::FocusMonitorWorkspace(arg) => { + send_message(&SocketMessage::FocusMonitorWorkspaceNumber( + arg.target_monitor, + arg.target_workspace, + ))?; + } + SubCommand::FocusNamedWorkspace(arg) => { + send_message(&SocketMessage::FocusNamedWorkspace(arg.workspace))?; + } + SubCommand::CloseWorkspace => { + send_message(&SocketMessage::CloseWorkspace)?; + } + SubCommand::CycleMonitor(arg) => { + send_message(&SocketMessage::CycleFocusMonitor(arg.cycle_direction))?; + } + SubCommand::CycleWorkspace(arg) => { + send_message(&SocketMessage::CycleFocusWorkspace(arg.cycle_direction))?; + } + SubCommand::CycleEmptyWorkspace(arg) => { + send_message(&SocketMessage::CycleFocusEmptyWorkspace( + arg.cycle_direction, + ))?; + } } Ok(())