diff --git a/justfile b/justfile index 7af0ca48..2ba71c05 100644 --- a/justfile +++ b/justfile @@ -1,13 +1,13 @@ export RUST_BACKTRACE := "full" -clean: - cargo clean - fmt: cargo +nightly fmt cargo +stable clippy prettier --write README.md +clean: + cargo clean + install target: cargo +stable install --path {{ target }} --locked --target-dir ~/.cargo/bin diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index fa3b69c5..6cb01d82 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -24,6 +24,31 @@ pub enum Sizing { Decrease, } +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq)] +pub struct WindowManagementBehaviour { + /// The current WindowContainerBehaviour to be used + pub current_behaviour: WindowContainerBehaviour, + /// Override of `current_behaviour` to open new windows as floating windows + /// that can be later toggled to tiled, when false it will default to + /// `current_behaviour` again. + pub float_override: bool, + /// Determines if a new window should be spawned floating when on the floating layer and the + /// floating layer behaviour is set to float. This value is always calculated when checking for + /// the management behaviour on a specific workspace. + pub floating_layer_override: bool, + /// The floating layer behaviour to be used if the float override is being used + pub floating_layer_behaviour: FloatingLayerBehaviour, + /// The `Placement` to be used when toggling a window to float + pub toggle_float_placement: Placement, + /// The `Placement` to be used when spawning a window on the floating layer with the + /// `FloatingLayerBehaviour` set to `FloatingLayerBehaviour::Float` + pub floating_layer_placement: Placement, + /// The `Placement` to be used when spawning a window with float override active + pub float_override_placement: Placement, + /// The `Placement` to be used when spawning a window that matches a 'floating_applications' rule + pub float_rule_placement: Placement, +} + #[derive( Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, )] @@ -35,6 +60,55 @@ pub enum WindowContainerBehaviour { Append, } +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +pub enum FloatingLayerBehaviour { + /// Tile new windows (unless they match a float rule or float override is active) + #[default] + Tile, + /// Float new windows + Float, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +pub enum Placement { + /// Does not change the size or position of the window + #[default] + None, + /// Center the window without changing the size + Center, + /// Center the window and resize it according to the `AspectRatio` + CenterAndResize, +} + +impl FloatingLayerBehaviour { + pub fn should_float(&self) -> bool { + match self { + FloatingLayerBehaviour::Tile => false, + FloatingLayerBehaviour::Float => true, + } + } +} + +impl Placement { + pub fn should_center(&self) -> bool { + match self { + Placement::None => false, + Placement::Center | Placement::CenterAndResize => true, + } + } + + pub fn should_resize(&self) -> bool { + match self { + Placement::None | Placement::Center => false, + Placement::CenterAndResize => true, + } + } +} + #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, Deserialize, Display)] #[serde(tag = "type", content = "content")] @@ -48,6 +122,8 @@ pub enum SocketMessage { ChangeLayout(DefaultLayout), TogglePause, ToggleMonocle, + ToggleFloat, + ToggleWorkspaceLayer, FocusWorkspaceNumber(usize), MoveContainerToWorkspaceNumber(usize), SendContainerToWorkspaceNumber(usize), diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index f6903de4..3055f20d 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -2,6 +2,8 @@ use crate::accessibility::error::AccessibilityError; use crate::core_graphics::error::CoreGraphicsError; +use crate::window::AspectRatio; +use crate::window::PredefinedAspectRatio; use core::pathext::PathExt; use lazy_static::lazy_static; use objc2_application_services::AXObserver; @@ -14,9 +16,12 @@ use objc2_core_foundation::CFString; use objc2_core_foundation::CGPoint; use objc2_core_foundation::CGRect; use objc2_core_foundation::CGSize; +use parking_lot::Mutex; +use std::collections::HashMap; use std::ops::Deref; use std::path::PathBuf; use std::ptr::NonNull; +use std::sync::Arc; use std::sync::atomic::AtomicI32; #[macro_use] @@ -55,6 +60,11 @@ lazy_static! { pub static ref DATA_DIR: PathBuf = dirs::data_local_dir() .expect("there is no local data directory") .join("komorebi"); + static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( + AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) + )); + static ref WINDOW_RESTORE_POSITIONS: Arc>> = + Arc::new(Mutex::new(HashMap::new())); } pub static DEFAULT_WORKSPACE_PADDING: AtomicI32 = AtomicI32::new(5); diff --git a/komorebi/src/macos_api.rs b/komorebi/src/macos_api.rs index 2bbba371..f47604bf 100644 --- a/komorebi/src/macos_api.rs +++ b/komorebi/src/macos_api.rs @@ -1,4 +1,7 @@ use crate::LibraryError; +use crate::accessibility::AccessibilityApi; +use crate::accessibility::attribute_constants::kAXFocusedApplicationAttribute; +use crate::accessibility::attribute_constants::kAXFocusedWindowAttribute; use crate::accessibility::attribute_constants::kAXPositionAttribute; use crate::accessibility::attribute_constants::kAXSizeAttribute; use crate::accessibility::error::AccessibilityApiError; @@ -17,6 +20,7 @@ use objc2_application_services::AXUIElement; use objc2_application_services::AXValue; use objc2_application_services::AXValueType; use objc2_core_foundation::CFDictionary; +use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFString; use objc2_core_foundation::CGRect; use std::collections::HashMap; @@ -129,9 +133,6 @@ impl MacosApi { let mut position_receiver = std::ptr::null(); let mut size_receiver = std::ptr::null(); - // let mut position_receiver = CGPoint::default(); - // let mut size_receiver = CGSize::default(); - unsafe { match AccessibilityApiError::from(element.copy_attribute_value( &CFString::from_static_str(kAXPositionAttribute), @@ -171,4 +172,33 @@ impl MacosApi { Ok(rect) } } + + pub fn foreground_window_id() -> Option { + unsafe { + let syswide = AXUIElement::new_system_wide(); + let app = AccessibilityApi::copy_attribute_value::( + &syswide, + kAXFocusedApplicationAttribute, + )?; + + let window = AccessibilityApi::copy_attribute_value::( + &app, + kAXFocusedWindowAttribute, + )?; + + AccessibilityApi::window_id(&window).ok() + } + } + + pub fn foreground_window() -> Option> { + unsafe { + let syswide = AXUIElement::new_system_wide(); + let app = AccessibilityApi::copy_attribute_value::( + &syswide, + kAXFocusedApplicationAttribute, + )?; + + AccessibilityApi::copy_attribute_value::(&app, kAXFocusedWindowAttribute) + } + } } diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index c0b1a712..2a1c96e2 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -5,9 +5,11 @@ use crate::core::default_layout::DefaultLayout; use crate::core::layout::Layout; use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; +use crate::macos_api::MacosApi; use crate::ring::Ring; use crate::workspace::Workspace; use crate::workspace::WorkspaceGlobals; +use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use color_eyre::eyre::eyre; use std::sync::atomic::Ordering; @@ -138,6 +140,91 @@ impl Monitor { .focused_workspace_mut() .ok_or_else(|| eyre!("there is no workspace"))?; + // if workspace.maximized_window().is_some() { + // return Err(eyre!("cannot move native maximized window to another monitor or workspace")); + // } + + let foreground_hwnd = + MacosApi::foreground_window_id().ok_or(eyre!("no foreground window"))?; + let floating_window_index = workspace + .floating_windows() + .iter() + .position(|w| w.id == foreground_hwnd); + + if let Some(idx) = floating_window_index { + if let Some(window) = workspace.floating_windows_mut().remove(idx) { + let workspaces = self.workspaces_mut(); + #[allow(clippy::option_if_let_else)] + let target_workspace = match workspaces.get_mut(target_workspace_idx) { + None => { + workspaces.resize(target_workspace_idx + 1, Workspace::default()); + workspaces.get_mut(target_workspace_idx).unwrap() + } + Some(workspace) => workspace, + }; + + target_workspace.floating_windows_mut().push_back(window); + target_workspace.layer = WorkspaceLayer::Floating; + } + } else { + let container = workspace + .remove_focused_container() + .ok_or_else(|| eyre!("there is no container"))?; + + let workspaces = self.workspaces_mut(); + + #[allow(clippy::option_if_let_else)] + let target_workspace = match workspaces.get_mut(target_workspace_idx) { + None => { + workspaces.resize(target_workspace_idx + 1, Workspace::default()); + workspaces.get_mut(target_workspace_idx).unwrap() + } + Some(workspace) => workspace, + }; + + if target_workspace.monocle_container.is_some() { + for container in target_workspace.containers_mut() { + container.restore()?; + } + + for window in target_workspace.floating_windows_mut() { + window.restore()?; + } + + target_workspace.reintegrate_monocle_container()?; + } + + target_workspace.layer = WorkspaceLayer::Tiling; + + if let Some(direction) = direction { + self.add_container_with_direction( + container, + Some(target_workspace_idx), + direction, + )?; + } else { + target_workspace.add_container_to_back(container); + } + } + + if follow { + self.focus_workspace(target_workspace_idx)?; + } + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn move_container_to_workspace1( + &mut self, + target_workspace_idx: usize, + follow: bool, + direction: Option, + ) -> eyre::Result<()> { + let workspace = self + .focused_workspace_mut() + .ok_or_else(|| eyre!("there is no workspace"))?; + let container = workspace .remove_focused_container() .ok_or_else(|| eyre!("there is no container"))?; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 66031711..01f7b26b 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -1,5 +1,8 @@ use crate::core::SocketMessage; +use crate::core::rect::Rect; +use crate::macos_api::MacosApi; use crate::window_manager::WindowManager; +use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use parking_lot::Mutex; use std::io::BufRead; @@ -57,12 +60,30 @@ impl WindowManager { message: SocketMessage, mut _reply: impl std::io::Write, ) -> eyre::Result<()> { + tracing::info!("processing command: {message}"); + match message { SocketMessage::FocusWindow(direction) => { - self.focus_container_in_direction(direction)?; + let focused_workspace = self.focused_workspace()?; + match focused_workspace.layer { + WorkspaceLayer::Tiling => { + self.focus_container_in_direction(direction)?; + } + WorkspaceLayer::Floating => { + self.focus_floating_window_in_direction(direction)?; + } + } } SocketMessage::MoveWindow(direction) => { - self.move_container_in_direction(direction)?; + let focused_workspace = self.focused_workspace()?; + match focused_workspace.layer { + WorkspaceLayer::Tiling => { + self.move_container_in_direction(direction)?; + } + WorkspaceLayer::Floating => { + self.move_floating_window_in_direction(direction)?; + } + } } SocketMessage::StackWindow(direction) => self.add_window_to_container(direction)?, SocketMessage::UnstackWindow => self.remove_window_from_container()?, @@ -91,6 +112,116 @@ impl WindowManager { self.move_container_to_workspace(workspace_idx, false, None)?; } SocketMessage::ToggleMonocle => self.toggle_monocle()?, + SocketMessage::ToggleFloat => self.toggle_float(false)?, + SocketMessage::ToggleWorkspaceLayer => { + let mouse_follows_focus = self.mouse_follows_focus; + let workspace = self.focused_workspace_mut()?; + + let mut to_focus = None; + match workspace.layer { + WorkspaceLayer::Tiling => { + workspace.layer = WorkspaceLayer::Floating; + tracing::info!("WorkspaceLayer is now Floating"); + + let focused_idx = workspace.focused_floating_window_idx(); + let mut window_idx_pairs = workspace + .floating_windows_mut() + .make_contiguous() + .iter_mut() + .enumerate() + .collect::>(); + + // Sort by window area + window_idx_pairs.sort_by_key(|(_, w)| { + let rect = + Rect::from(MacosApi::window_rect(&w.element).unwrap_or_default()); + rect.right * rect.bottom + }); + window_idx_pairs.reverse(); + + for (i, window) in window_idx_pairs { + if i == focused_idx { + to_focus = Some(window.clone()); + } else { + window.restore()?; + window.raise()?; + } + } + + if let Some(focused_window) = &mut to_focus { + // The focused window should be the last one raised to make sure it is + // on top + focused_window.restore()?; + focused_window.raise()?; + } + + for container in workspace.containers() { + if let Some(_window) = container.focused_window() { + // todo: figure out z order + // window.lower()?; + } + } + + if let Some(monocle) = &workspace.monocle_container + && let Some(_window) = monocle.focused_window() + { + // todo: figure out z order + // window.lower()?; + } + } + WorkspaceLayer::Floating => { + workspace.layer = WorkspaceLayer::Tiling; + tracing::info!("WorkspaceLayer is now Tiling"); + + if let Some(monocle) = &workspace.monocle_container { + if let Some(window) = monocle.focused_window() { + to_focus = Some(window.clone()); + window.raise()?; + } + + for window in workspace.floating_windows_mut() { + window.hide()?; + } + } else { + let focused_container_idx = workspace.focused_container_idx(); + for (i, container) in workspace.containers_mut().iter_mut().enumerate() + { + if let Some(window) = container.focused_window() { + if i == focused_container_idx { + to_focus = Some(window.clone()); + } + + window.raise()?; + } + } + + let mut window_idx_pairs = workspace + .floating_windows_mut() + .make_contiguous() + .iter_mut() + .collect::>(); + + // Sort by window area + window_idx_pairs.sort_by_key(|w| { + let rect = Rect::from( + MacosApi::window_rect(&w.element).unwrap_or_default(), + ); + rect.right * rect.bottom + }); + + for window in window_idx_pairs { + // todo: figure out z order + window.hide()?; + // window.lower()?; + } + } + } + }; + + if let Some(window) = to_focus { + window.focus(mouse_follows_focus)?; + } + } } Ok(()) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 2ad477af..9543f750 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -1,8 +1,11 @@ use crate::accessibility::AccessibilityApi; use crate::accessibility::notification_constants::AccessibilityNotification; +use crate::core::default_layout::DefaultLayout; +use crate::core::layout::Layout; use crate::window::Window; use crate::window_manager::WindowManager; use crate::window_manager_event::WindowManagerEvent; +use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use parking_lot::Mutex; use std::sync::Arc; @@ -38,15 +41,66 @@ impl WindowManager { return Ok(()); } - tracing::info!("processing event: {event}"); + tracing::info!( + "processing event: {event} for process {}", + event.process_id() + ); match event { WindowManagerEvent::FocusChange(notification, process_id, _) => { let application = self.application(process_id)?; if let Some(window_id) = application.main_window_id() { - self.focused_workspace_mut()? - .focus_container_by_window(window_id)?; + // todo: figure out if this applies on macOS too + // don't want to trigger the full workspace updates when there are no managed + // containers - this makes floating windows on empty workspaces go into very + // annoying focus change loops which prevents users from interacting with them + if !matches!( + self.focused_workspace()?.layout, + Layout::Default(DefaultLayout::Scrolling) + ) && !self.focused_workspace()?.containers().is_empty() + { + self.update_focused_workspace(self.mouse_follows_focus, false)?; + } + + let workspace = self.focused_workspace_mut()?; + let floating_window_idx = workspace + .floating_windows() + .iter() + .position(|w| w.id == window_id); + + match floating_window_idx { + None => { + // if let Some(w) = workspace.maximized_window() { + // if w.hwnd == window_id { + // return Ok(()); + // } + // } + + if let Some(monocle) = &workspace.monocle_container { + if let Some(window) = monocle.focused_window() { + window.focus(false)?; + } + } else { + workspace.focus_container_by_window(window_id)?; + } + + workspace.layer = WorkspaceLayer::Tiling; + + if matches!( + self.focused_workspace()?.layout, + Layout::Default(DefaultLayout::Scrolling) + ) && !self.focused_workspace()?.containers().is_empty() + { + self.update_focused_workspace(self.mouse_follows_focus, false)?; + } + } + Some(idx) => { + if let Some(_window) = workspace.floating_windows().get(idx) { + workspace.layer = WorkspaceLayer::Floating; + } + } + } } if matches!(notification, AccessibilityNotification::AXMainWindowChanged) { @@ -54,6 +108,7 @@ impl WindowManager { self.update_focused_workspace(false, false)?; } } + // todo: upate this to work with floating applications / rules WindowManagerEvent::Show(_, process_id) => { let mut window_id = None; let mut window_element = None; diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 1e9235a3..65fd6732 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -1,7 +1,10 @@ use crate::AccessibilityObserver; use crate::AccessibilityUiElement; +use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO; use crate::LibraryError; +use crate::WINDOW_RESTORE_POSITIONS; use crate::accessibility::AccessibilityApi; +use crate::accessibility::attribute_constants::kAXFocusedAttribute; use crate::accessibility::attribute_constants::kAXMainAttribute; use crate::accessibility::attribute_constants::kAXMinimizedAttribute; use crate::accessibility::attribute_constants::kAXPositionAttribute; @@ -42,9 +45,14 @@ use objc2_core_graphics::kCGWindowBounds; use objc2_core_graphics::kCGWindowName; use objc2_core_graphics::kCGWindowOwnerName; use objc2_core_graphics::kCGWindowOwnerPID; +use serde::Deserialize; +use serde::Serialize; +use std::collections::hash_map::Entry; use std::ffi::c_void; use std::ptr::NonNull; use std::str::FromStr; +use strum::Display; +use strum::EnumString; use tracing::instrument; const NOTIFICATIONS: &[&str] = &[ @@ -143,10 +151,9 @@ impl WindowInfo { #[allow(unused)] pub struct Window { pub id: u32, - element: AccessibilityUiElement, + pub element: AccessibilityUiElement, pub application: Application, observer: AccessibilityObserver, - pub restore_point: Option<(f32, f32)>, } impl Drop for Window { @@ -181,7 +188,6 @@ impl Window { element: AccessibilityUiElement(element), application, observer: AccessibilityObserver(observer), - restore_point: None, }) } @@ -208,11 +214,14 @@ impl Window { #[tracing::instrument(skip_all)] pub fn hide(&mut self) -> Result<(), AccessibilityError> { - // I don't love this, but it's basically what Aerospace does in lieu of an actual "Hide" API - if self.restore_point.is_none() { + let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock(); + if let Entry::Vacant(entry) = window_restore_positions.entry(self.id) { let rect = MacosApi::window_rect(&self.element)?; if let Some(monitor_size) = CoreGraphicsApi::display_bounds_for_window_rect(rect) { - self.restore_point = Some((rect.origin.x as f32, rect.origin.y as f32)); + entry.insert(rect); + drop(window_restore_positions); + + // I don't love this, but it's basically what Aerospace does in lieu of an actual "Hide" API let hidden_rect = hidden_frame_bottom_left(monitor_size, rect.size); tracing::debug!( @@ -245,20 +254,22 @@ impl Window { #[tracing::instrument(skip_all)] pub fn restore(&mut self) -> Result<(), AccessibilityError> { - let mut should_unset_restore_point = false; - if let Some((x, y)) = self.restore_point { + let mut should_remove_restore_position = false; + let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock(); + if let Some(cg_rect) = window_restore_positions.get(&self.id) { tracing::debug!( - "restoring {:?} to point {x},{y}", + "restoring {:?} to {cg_rect:?}", self.title() .unwrap_or_else(|| String::from("")) ); - self.set_point(CGPoint::new(x as CGFloat, y as CGFloat))?; - should_unset_restore_point = true; + self.set_point(cg_rect.origin)?; + self.set_size(cg_rect.size)?; + should_remove_restore_position = true; } - if should_unset_restore_point { - self.restore_point = None; + if should_remove_restore_position { + window_restore_positions.remove(&self.id); } Ok(()) @@ -296,6 +307,13 @@ impl Window { Ok(()) } + pub fn raise(&self) -> Result<(), AccessibilityError> { + let cf_boolean = CFBoolean::new(true); + let value = &**cf_boolean; + AccessibilityApi::set_attribute_cf_value(&self.element, kAXMainAttribute, value)?; + AccessibilityApi::set_attribute_cf_value(&self.element, kAXFocusedAttribute, value) + } + pub fn set_point(&self, point: CGPoint) -> Result<(), AccessibilityError> { AccessibilityApi::set_attribute_ax_value( &self.element, @@ -313,6 +331,30 @@ impl Window { size, ) } + + pub fn center(&mut self, work_area: &Rect, resize: bool) -> Result<(), AccessibilityError> { + let (target_width, target_height) = if resize { + let (aspect_ratio_width, aspect_ratio_height) = FLOATING_WINDOW_TOGGLE_ASPECT_RATIO + .lock() + .width_and_height(); + let target_height = work_area.bottom / 2; + let target_width = (target_height * aspect_ratio_width) / aspect_ratio_height; + (target_width, target_height) + } else { + let current_rect = Rect::from(MacosApi::window_rect(&self.element)?); + (current_rect.right, current_rect.bottom) + }; + + let x = work_area.left + ((work_area.right - target_width) / 2); + let y = work_area.top + ((work_area.bottom - target_height) / 2); + + self.set_position(&Rect { + left: x, + top: y, + right: target_width, + bottom: target_height, + }) + } } impl From<&CFDictionary> for WindowInfo { @@ -376,3 +418,42 @@ impl From<&CFDictionary> for WindowBounds { } } } + +#[derive(Copy, Clone, Debug, Display, EnumString, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] +pub enum AspectRatio { + /// A predefined aspect ratio + Predefined(PredefinedAspectRatio), + /// A custom W:H aspect ratio + Custom(i32, i32), +} + +impl Default for AspectRatio { + fn default() -> Self { + AspectRatio::Predefined(PredefinedAspectRatio::default()) + } +} + +#[derive(Copy, Clone, Debug, Default, Display, EnumString, Serialize, Deserialize, PartialEq)] +pub enum PredefinedAspectRatio { + /// 21:9 + Ultrawide, + /// 16:9 + Widescreen, + /// 4:3 + #[default] + Standard, +} + +impl AspectRatio { + pub fn width_and_height(self) -> (i32, i32) { + match self { + AspectRatio::Predefined(predefined) => match predefined { + PredefinedAspectRatio::Ultrawide => (21, 9), + PredefinedAspectRatio::Widescreen => (16, 9), + PredefinedAspectRatio::Standard => (4, 3), + }, + AspectRatio::Custom(w, h) => (w, h), + } + } +} diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 4dc5f2a6..2f440fb0 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -4,6 +4,8 @@ use crate::LibraryError; use crate::accessibility::AccessibilityApi; use crate::application::Application; use crate::container::Container; +use crate::core::Placement; +use crate::core::WindowManagementBehaviour; use crate::core::cycle_direction::CycleDirection; use crate::core::default_layout::DefaultLayout; use crate::core::layout::Layout; @@ -15,6 +17,7 @@ use crate::ring::Ring; use crate::window::Window; use crate::window_manager_event::WindowManagerEvent; use crate::workspace::Workspace; +use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use color_eyre::eyre::eyre; use crossbeam_channel::Receiver; @@ -34,6 +37,8 @@ pub struct WindowManager { pub run_loop: CoreFoundationRunLoop, pub command_listener: UnixListener, pub is_paused: bool, + pub resize_delta: i32, + pub window_management_behaviour: WindowManagementBehaviour, pub mouse_follows_focus: bool, pub work_area_offset: Option, pub incoming_events: Receiver, @@ -43,6 +48,7 @@ pub struct WindowManager { impl_ring_elements!(WindowManager, Monitor); impl WindowManager { + #[allow(clippy::field_reassign_with_default)] pub fn new( run_loop: &CFRetained, incoming: Receiver, @@ -62,12 +68,18 @@ impl WindowManager { let listener = UnixListener::bind(&socket)?; + // todo: undo this when we get config + let mut behaviour = WindowManagementBehaviour::default(); + behaviour.toggle_float_placement = Placement::CenterAndResize; + Ok(Self { monitors: Ring::default(), applications: Default::default(), run_loop: CoreFoundationRunLoop(run_loop.clone()), command_listener: listener, is_paused: false, + resize_delta: 50, + window_management_behaviour: behaviour, mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -93,6 +105,265 @@ impl WindowManager { } } + #[tracing::instrument(skip(self))] + pub fn focus_floating_window_in_direction( + &mut self, + direction: OperationDirection, + ) -> eyre::Result<()> { + let mouse_follows_focus = self.mouse_follows_focus; + let focused_workspace = self.focused_workspace_mut()?; + + let mut target_idx = None; + let len = focused_workspace.floating_windows().len(); + + if len > 1 { + let focused_window_id = + MacosApi::foreground_window_id().ok_or(eyre!("no foreground window"))?; + let focused_rect = Rect::from(MacosApi::window_rect( + MacosApi::foreground_window() + .ok_or(eyre!("no foreground window"))? + .as_ref(), + )?); + + match direction { + OperationDirection::Left => { + let mut windows_in_direction = focused_workspace + .floating_windows() + .iter() + .enumerate() + .flat_map(|(idx, w)| { + (w.id != focused_window_id).then_some( + MacosApi::window_rect(&w.element) + .ok() + .map(|r| (idx, Rect::from(r))), + ) + }) + .flatten() + .flat_map(|(idx, r)| { + (r.left < focused_rect.left) + .then_some((idx, i32::abs(r.left - focused_rect.left))) + }) + .collect::>(); + + // Sort by distance to focused + windows_in_direction.sort_by_key(|(_, d)| (*d as f32 * 1000.0).trunc() as i32); + + if let Some((idx, _)) = windows_in_direction.first() { + target_idx = Some(*idx); + } + } + OperationDirection::Right => { + let mut windows_in_direction = focused_workspace + .floating_windows() + .iter() + .enumerate() + .flat_map(|(idx, w)| { + (w.id != focused_window_id).then_some( + MacosApi::window_rect(&w.element) + .ok() + .map(|r| (idx, Rect::from(r))), + ) + }) + .flatten() + .flat_map(|(idx, r)| { + (r.left > focused_rect.left) + .then_some((idx, i32::abs(r.left - focused_rect.left))) + }) + .collect::>(); + + // Sort by distance to focused + windows_in_direction.sort_by_key(|(_, d)| (*d as f32 * 1000.0).trunc() as i32); + + if let Some((idx, _)) = windows_in_direction.first() { + target_idx = Some(*idx); + } + } + OperationDirection::Up => { + let mut windows_in_direction = focused_workspace + .floating_windows() + .iter() + .enumerate() + .flat_map(|(idx, w)| { + (w.id != focused_window_id).then_some( + MacosApi::window_rect(&w.element) + .ok() + .map(|r| (idx, Rect::from(r))), + ) + }) + .flatten() + .flat_map(|(idx, r)| { + (r.top < focused_rect.top) + .then_some((idx, i32::abs(r.top - focused_rect.top))) + }) + .collect::>(); + + // Sort by distance to focused + windows_in_direction.sort_by_key(|(_, d)| (*d as f32 * 1000.0).trunc() as i32); + + if let Some((idx, _)) = windows_in_direction.first() { + target_idx = Some(*idx); + } + } + OperationDirection::Down => { + let mut windows_in_direction = focused_workspace + .floating_windows() + .iter() + .enumerate() + .flat_map(|(idx, w)| { + (w.id != focused_window_id).then_some( + MacosApi::window_rect(&w.element) + .ok() + .map(|r| (idx, Rect::from(r))), + ) + }) + .flatten() + .flat_map(|(idx, r)| { + (r.top > focused_rect.top) + .then_some((idx, i32::abs(r.top - focused_rect.top))) + }) + .collect::>(); + + // Sort by distance to focused + windows_in_direction.sort_by_key(|(_, d)| (*d as f32 * 1000.0).trunc() as i32); + + if let Some((idx, _)) = windows_in_direction.first() { + target_idx = Some(*idx); + } + } + }; + } + + if let Some(idx) = target_idx { + focused_workspace.floating_windows.focus(idx); + if let Some(window) = focused_workspace.floating_windows().get(idx) { + window.focus(mouse_follows_focus)?; + } + return Ok(()); + } + + // let mut cross_monitor_monocle_or_max = false; + + // let workspace_idx = self.focused_workspace_idx()?; + + // this is for when we are scrolling across workspaces like PaperWM + // if matches!( + // self.cross_boundary_behaviour, + // CrossBoundaryBehaviour::Workspace + // ) && matches!( + // direction, + // OperationDirection::Left | OperationDirection::Right + // ) { + // let workspace_count = if let Some(monitor) = self.focused_monitor() { + // monitor.workspaces().len() + // } else { + // 1 + // }; + // + // let next_idx = match direction { + // OperationDirection::Left => match workspace_idx { + // 0 => workspace_count - 1, + // n => n - 1, + // }, + // OperationDirection::Right => match workspace_idx { + // n if n == workspace_count - 1 => 0, + // n => n + 1, + // }, + // _ => workspace_idx, + // }; + // + // self.focus_workspace(next_idx)?; + // + // if let Ok(focused_workspace) = self.focused_workspace_mut() { + // if focused_workspace.monocle_container.is_none() { + // match direction { + // OperationDirection::Left => match focused_workspace.layout { + // Layout::Default(layout) => { + // let target_index = + // layout.rightmost_index(focused_workspace.containers().len()); + // focused_workspace.focus_container(target_index); + // } + // }, + // OperationDirection::Right => match focused_workspace.layout { + // Layout::Default(layout) => { + // let target_index = + // layout.leftmost_index(focused_workspace.containers().len()); + // focused_workspace.focus_container(target_index); + // } + // }, + // _ => {} + // }; + // } + // } + // + // return Ok(()); + // } + + // if there is no floating_window in that direction for this workspace + // let monitor_idx = self + // .monitor_idx_in_direction(direction) + // .ok_or_else(|| eyre!("there is no container or monitor in this direction"))?; + // + // self.focus_monitor(monitor_idx)?; + // let mouse_follows_focus = self.mouse_follows_focus; + // + // if let Ok(focused_workspace) = self.focused_workspace_mut() { + // // if let Some(window) = focused_workspace.maximized_window() { + // // window.focus(mouse_follows_focus)?; + // // cross_monitor_monocle_or_max = true; + // // } else + // if let Some(monocle) = focused_workspace.monocle_container { + // if let Some(window) = monocle.focused_window() { + // window.focus(mouse_follows_focus)?; + // cross_monitor_monocle_or_max = true; + // } + // } else if focused_workspace.layer == WorkspaceLayer::Tiling { + // match direction { + // OperationDirection::Left => match focused_workspace.layout { + // Layout::Default(layout) => { + // let target_index = + // layout.rightmost_index(focused_workspace.containers().len()); + // focused_workspace.focus_container(target_index); + // } + // }, + // OperationDirection::Right => match focused_workspace.layout { + // Layout::Default(layout) => { + // let target_index = + // layout.leftmost_index(focused_workspace.containers().len()); + // focused_workspace.focus_container(target_index); + // } + // }, + // _ => {} + // }; + // } + // } + // + // if !cross_monitor_monocle_or_max { + // let ws = self.focused_workspace_mut()?; + // if ws.is_empty() { + // // This is to remove focus from the previous monitor + // let desktop_window = Window::from(MacosApi::desktop_window()?); + // + // match MacosApi::raise_and_focus_window(desktop_window.id) { + // Ok(()) => {} + // Err(error) => { + // tracing::warn!("{} {}:{}", error, file!(), line!()); + // } + // } + // } else if ws.layer == WorkspaceLayer::Floating && !ws.floating_windows().is_empty() { + // if let Some(window) = ws.focused_floating_window() { + // window.focus(self.mouse_follows_focus)?; + // } + // } else { + // ws.layer = WorkspaceLayer::Tiling; + // if let Ok(focused_window) = self.focused_window() { + // focused_window.focus(self.mouse_follows_focus)?; + // } + // } + // } + + Ok(()) + } + #[tracing::instrument(skip(self))] pub fn focus_container_in_direction( &mut self, @@ -117,6 +388,85 @@ impl WindowManager { Ok(()) } + #[tracing::instrument(skip(self))] + pub fn move_floating_window_in_direction( + &mut self, + direction: OperationDirection, + ) -> eyre::Result<()> { + let mouse_follows_focus = self.mouse_follows_focus; + + let mut focused_monitor_work_area = self.focused_monitor_work_area()?; + let border_offset = 0; + let border_width = 0; + focused_monitor_work_area.left += border_offset; + focused_monitor_work_area.left += border_width; + focused_monitor_work_area.top += border_offset; + focused_monitor_work_area.top += border_width; + focused_monitor_work_area.right -= border_offset * 2; + focused_monitor_work_area.right -= border_width * 2; + focused_monitor_work_area.bottom -= border_offset * 2; + focused_monitor_work_area.bottom -= border_width * 2; + + let focused_workspace = self.focused_workspace()?; + let delta = self.resize_delta; + + let focused_window_id = + MacosApi::foreground_window_id().ok_or(eyre!("no foreground window"))?; + for window in focused_workspace.floating_windows().iter() { + if window.id == focused_window_id { + let mut rect = Rect::from(MacosApi::window_rect(&window.element)?); + match direction { + OperationDirection::Left => { + if rect.left - delta < focused_monitor_work_area.left { + rect.left = focused_monitor_work_area.left; + } else { + rect.left -= delta; + } + } + OperationDirection::Right => { + if rect.left + delta + rect.right + > focused_monitor_work_area.left + focused_monitor_work_area.right + { + rect.left = focused_monitor_work_area.left + + focused_monitor_work_area.right + - rect.right; + } else { + rect.left += delta; + } + } + OperationDirection::Up => { + if rect.top - delta < focused_monitor_work_area.top { + rect.top = focused_monitor_work_area.top; + } else { + rect.top -= delta; + } + } + OperationDirection::Down => { + if rect.top + delta + rect.bottom + > focused_monitor_work_area.top + focused_monitor_work_area.bottom + { + rect.top = focused_monitor_work_area.top + + focused_monitor_work_area.bottom + - rect.bottom; + } else { + rect.top += delta; + } + } + } + + window.set_position(&rect)?; + + if mouse_follows_focus { + MacosApi::center_cursor_in_rect(&rect)?; + } + + break; + } + } + + Ok(()) + } + #[tracing::instrument(skip(self))] pub fn move_container_in_direction( &mut self, @@ -262,6 +612,20 @@ impl WindowManager { .ok_or_else(|| eyre!("there is no window")) } + pub fn focused_monitor_size(&self) -> eyre::Result { + Ok(self + .focused_monitor() + .ok_or_else(|| eyre!("there is no monitor"))? + .size) + } + + pub fn focused_monitor_work_area(&self) -> eyre::Result { + Ok(self + .focused_monitor() + .ok_or_else(|| eyre!("there is no monitor"))? + .work_area_size) + } + pub fn extract_minimized_window(&mut self, window_id: u32) -> eyre::Result<()> { let workspace = self.focused_workspace_mut()?; let window = workspace.remove_window(window_id)?; @@ -494,4 +858,66 @@ impl WindowManager { workspace.reintegrate_monocle_container() } + + #[tracing::instrument(skip(self))] + pub fn toggle_float(&mut self, force_float: bool) -> eyre::Result<()> { + let window_id = MacosApi::foreground_window_id().ok_or(eyre!("no foreground window"))?; + + let workspace = self.focused_workspace_mut()?; + if workspace.monocle_container.is_some() { + tracing::warn!("ignoring toggle-float command while workspace has a monocle container"); + return Ok(()); + } + + let mut is_floating_window = false; + + for window in workspace.floating_windows() { + if window.id == window_id { + is_floating_window = true; + } + } + + if is_floating_window && !force_float { + workspace.layer = WorkspaceLayer::Tiling; + self.unfloat_window()?; + } else { + workspace.layer = WorkspaceLayer::Floating; + self.float_window()?; + } + + self.update_focused_workspace(is_floating_window, true) + } + + #[tracing::instrument(skip(self))] + pub fn float_window(&mut self) -> eyre::Result<()> { + tracing::info!("floating window"); + + let mouse_follows_focus = self.mouse_follows_focus; + let work_area = self.focused_monitor_work_area()?; + + let toggle_float_placement = self.window_management_behaviour.toggle_float_placement; + + let workspace = self.focused_workspace_mut()?; + workspace.new_floating_window()?; + + let window = workspace + .floating_windows_mut() + .back_mut() + .ok_or_else(|| eyre!("there is no floating window"))?; + + if toggle_float_placement.should_center() { + window.center(&work_area, toggle_float_placement.should_resize())?; + } + window.focus(mouse_follows_focus)?; + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn unfloat_window(&mut self) -> eyre::Result<()> { + tracing::info!("unfloating window"); + + let workspace = self.focused_workspace_mut()?; + workspace.new_container_for_floating_window() + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 8a350691..df3f733b 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -1,4 +1,5 @@ use crate::container::Container; +use crate::core::FloatingLayerBehaviour; use crate::core::WindowContainerBehaviour; use crate::core::arrangement::Axis; use crate::core::default_layout::DefaultLayout; @@ -7,41 +8,71 @@ use crate::core::layout::Layout; use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; use crate::lockable_sequence::LockableSequence; +use crate::macos_api::MacosApi; use crate::ring::Ring; use crate::window::Window; use color_eyre::eyre; use color_eyre::eyre::eyre; +use serde::Deserialize; +use serde::Serialize; +use std::fmt::Display; +use std::fmt::Formatter; use std::num::NonZeroUsize; -impl_ring_elements!(Workspace, Container); - #[derive(Debug, Clone)] pub struct Workspace { pub containers: Ring, pub monocle_container: Option, pub monocle_container_restore_idx: Option, - pub workspace_padding: Option, - pub container_padding: Option, - pub resize_dimensions: Vec>, + pub maximized_window: Option, + pub maximized_window_restore_idx: Option, + pub floating_windows: Ring, pub layout: Layout, - pub work_area_offset: Option, - pub latest_layout: Vec, - pub layout_flip: Option, pub layout_options: Option, pub layout_rules: Vec<(usize, Layout)>, - pub globals: WorkspaceGlobals, + pub layout_flip: Option, + pub workspace_padding: Option, + pub container_padding: Option, + pub latest_layout: Vec, + pub resize_dimensions: Vec>, pub tile: bool, + pub work_area_offset: Option, pub apply_window_based_work_area_offset: bool, pub window_container_behaviour: Option, pub window_container_behaviour_rules: Option>, + pub float_override: Option, + pub globals: WorkspaceGlobals, + pub layer: WorkspaceLayer, + pub floating_layer_behaviour: Option, } +#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub enum WorkspaceLayer { + #[default] + Tiling, + Floating, +} + +impl Display for WorkspaceLayer { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + WorkspaceLayer::Tiling => write!(f, "Tiling"), + WorkspaceLayer::Floating => write!(f, "Floating"), + } + } +} + +impl_ring_elements!(Workspace, Container); +impl_ring_elements!(Workspace, Window, "floating_window"); + impl Default for Workspace { fn default() -> Self { Self { containers: Default::default(), monocle_container: None, monocle_container_restore_idx: None, + maximized_window: None, + maximized_window_restore_idx: None, workspace_padding: None, container_padding: None, resize_dimensions: vec![], @@ -52,10 +83,14 @@ impl Default for Workspace { layout_options: None, layout_rules: vec![], globals: Default::default(), + layer: Default::default(), tile: true, apply_window_based_work_area_offset: true, window_container_behaviour: None, window_container_behaviour_rules: None, + floating_windows: Default::default(), + float_override: None, + floating_layer_behaviour: None, } } } @@ -348,11 +383,30 @@ impl Workspace { } pub fn hide(&mut self, omit: Option) -> eyre::Result<()> { + for window in self.floating_windows_mut().iter_mut().rev() { + let mut should_hide = omit.is_none(); + + if !should_hide + && let Some(omit) = omit + && omit != window.id + { + should_hide = true + } + + if should_hide { + window.hide()?; + } + } + for container in self.containers_mut() { container.hide(omit)?; } - if let Some(container) = self.monocle_container.as_mut() { + // if let Some(window) = self.maximized_window() { + // window.hide(); + // } + + if let Some(container) = &mut self.monocle_container { container.hide(omit)?; } @@ -360,8 +414,9 @@ impl Workspace { } pub fn restore(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { - if let Some(container) = self.monocle_container.as_mut() { + if let Some(container) = &mut self.monocle_container { container.restore()?; + if let Some(window) = container.focused_window() { window.focus(mouse_follows_focus)?; } @@ -386,8 +441,28 @@ impl Workspace { container.focus_window(container.focused_window_idx()); } + for window in self.floating_windows_mut() { + window.restore()?; + } + // Do this here to make sure that an error doesn't stop the restoration of other windows + // Maximised windows and floating windows should always be drawn at the top of the Z order + // when switching to a workspace if let Some(window) = to_focus { - window.focus(mouse_follows_focus)?; + if + /* self.maximized_window().is_none() && */ + matches!(self.layer, WorkspaceLayer::Tiling) { + window.focus(mouse_follows_focus)?; + // } else if let Some(maximized_window) = self.maximized_window() { + // maximized_window.restore(); + // maximized_window.focus(mouse_follows_focus)?; + } else if let Some(floating_window) = self.focused_floating_window() { + floating_window.focus(mouse_follows_focus)?; + } + // } else if let Some(maximized_window) = self.maximized_window() { + // maximized_window.restore(); + // maximized_window.focus(mouse_follows_focus)?; + } else if let Some(floating_window) = self.focused_floating_window() { + floating_window.focus(mouse_follows_focus)?; } Ok(()) @@ -476,6 +551,97 @@ impl Workspace { Ok(()) } + + pub fn new_floating_window(&mut self) -> eyre::Result<()> { + let window = if let Some(monocle_container) = &mut self.monocle_container { + let window = monocle_container + .remove_focused_window() + .ok_or_else(|| eyre!("there is no window"))?; + + if monocle_container.windows().is_empty() { + self.monocle_container = None; + self.monocle_container_restore_idx = None; + } else { + monocle_container.load_focused_window()?; + } + + window + } else { + let focused_idx = self.focused_container_idx(); + + let container = self + .focused_container_mut() + .ok_or_else(|| eyre!("there is no container"))?; + + let window = container + .remove_focused_window() + .ok_or_else(|| eyre!("there is no window"))?; + + if container.windows().is_empty() { + self.remove_container_by_idx(focused_idx); + + if focused_idx == self.containers().len() { + self.focus_container(focused_idx.saturating_sub(1)); + } + } else { + container.load_focused_window()?; + } + + window + }; + + self.floating_windows_mut().push_back(window); + + Ok(()) + } + + pub fn new_container_for_floating_window(&mut self) -> eyre::Result<()> { + let focused_idx = self.focused_container_idx(); + let window = self + .remove_focused_floating_window() + .ok_or_else(|| eyre!("there is no floating window"))?; + + let mut container = Container::default(); + container.add_window(&window)?; + + self.insert_container_at_idx(focused_idx, container); + + Ok(()) + } + + pub fn remove_focused_floating_window(&mut self) -> Option { + let window_id = MacosApi::foreground_window_id()?; + + let mut idx = None; + for (i, window) in self.floating_windows().iter().enumerate() { + if window_id == window.id { + idx = Option::from(i); + } + } + + match idx { + None => None, + Some(idx) => { + if self.floating_windows().get(idx).is_some() { + self.focus_previous_floating_window(); + self.floating_windows_mut().remove(idx) + } else { + None + } + } + } + } + + pub fn focus_previous_floating_window(&mut self) { + let focused_idx = self.focused_floating_window_idx(); + self.focus_floating_window(focused_idx.saturating_sub(1)); + } + + pub fn focus_floating_window(&mut self, idx: usize) { + tracing::info!("focusing floating window"); + + self.floating_windows.focus(idx); + } } impl Workspace { diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 56edffe8..b789ae4d 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -105,6 +105,10 @@ enum SubCommand { TogglePause, /// Toggle monocle mode for the focused container ToggleMonocle, + /// Toggle floating mode for the focused window + ToggleFloat, + /// Toggle between the Tiling and Floating layers on the focused workspace + ToggleWorkspaceLayer, /// Set the layout on the focused workspace #[clap(arg_required_else_help = true)] ChangeLayout(ChangeLayout), @@ -156,6 +160,12 @@ fn main() -> eyre::Result<()> { SubCommand::ToggleMonocle => { send_message(&SocketMessage::ToggleMonocle)?; } + SubCommand::ToggleFloat => { + send_message(&SocketMessage::ToggleFloat)?; + } + SubCommand::ToggleWorkspaceLayer => { + send_message(&SocketMessage::ToggleWorkspaceLayer)?; + } } Ok(())