feat(wm): implement various monitor & ws focus cmds

This commit implements the CycleFocusMonitor, CycleFocusWorkspace,
CycleFocusEmptyWorkspace, FocusMonitorNumber, FocusMonitorAtCursor,
FocusLastWorkspace, CloseWorkspace, FocusWorkspaceNumbers,
FocusMonitorWorkspaceNumber and FocusNamedWorkspace SocketMessage
variants.

Largely a lift-and-shift from komorebi.

Had to implement some utility functions in MacosApi to retrieve a
monitor ID from the current cursor position.

None of the monitor-related system code has been tested on macOS since I
only have a single monitor to work with right now.
This commit is contained in:
LGUG2Z committed 2025-09-19 11:03:30 -07:00
1 parent e01fc55134
commit e883f4a161
7 files changed
+409 -2

No files matched your search

+10
View File
@@ -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),
+24
View File
@@ -83,6 +83,30 @@ impl CoreGraphicsApi {
.map(|display| CoreGraphicsApi::display_bounds(*display))
}
pub fn display_with_point(point: CGPoint) -> Option<u32> {
let mut displays: Vec<u32> = 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<CFRetained<CFArray>> {
unsafe {
CGWindowListCopyWindowInfo(
+13
View File
@@ -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::<AXUIElement>(&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<u32> {
CoreGraphicsApi::display_with_point(point)
}
}
+223
View File
@@ -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)?;
}
+41
View File
@@ -1303,4 +1303,45 @@ impl WindowManager {
None
}
pub fn monitor_idx_from_current_pos(&mut self) -> Option<usize> {
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
}
}
+2
View File
@@ -21,6 +21,7 @@ use std::num::NonZeroUsize;
#[derive(Debug, Clone)]
pub struct Workspace {
pub name: Option<String>,
pub containers: Ring<Container>,
pub monocle_container: Option<Container>,
pub monocle_container_restore_idx: Option<usize>,
@@ -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,
+96 -2
View File
@@ -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(())