GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: implement `focus_workspace` command
Lars Bergerd8db6b4a7b50
diff --git a/packages/wm/src/app_command.rs b/packages/wm/src/app_command.rsindex 30472ae9..199e199c 100644--- a/packages/wm/src/app_command.rs+++ b/packages/wm/src/app_command.rs@@ -19,6 +19,7 @@ use crate::{WindowState,},wm_state::WmState,+ workspaces::commands::{focus_workspace, FocusWorkspaceTarget},};#[derive(Clone, Debug, Parser)]@@ -202,20 +203,24 @@ impl InvokeCommand {todo!()}- if let Some(workspace) = &args.workspace {- todo!()+ if let Some(name) = &args.workspace {+ focus_workspace(+ FocusWorkspaceTarget::Name(name.to_string()),+ state,+ config,+ )?;}if args.next_workspace {- todo!()+ focus_workspace(FocusWorkspaceTarget::Next, state, config)?;}if args.prev_workspace {- todo!()+ focus_workspace(FocusWorkspaceTarget::Previous, state, config)?;}if args.recent_workspace {- todo!()+ focus_workspace(FocusWorkspaceTarget::Recent, state, config)?;}Ok(())diff --git a/packages/wm/src/common/rect.rs b/packages/wm/src/common/rect.rsindex c34ea028..7e7667f5 100644--- a/packages/wm/src/common/rect.rs+++ b/packages/wm/src/common/rect.rs@@ -80,4 +80,18 @@ impl Rect {self.bottom + delta.bottom.to_pixels(self.height()),)}++ // Gets whether the x-coordinate overlaps with the x-coordinate of the+ // other rect.+ pub fn has_overlap_x(&self, other: &Rect) -> bool {+ !(self.x() + self.width() <= other.x()+ || other.x() + other.width() <= self.x())+ }++ // Gets whether the y-coordinate overlaps with the y-coordinate of the+ // other rect.+ pub fn has_overlap_y(&self, other: &Rect) -> bool {+ !(self.y() + self.height() <= other.y()+ || other.y() + other.height() <= self.y())+ }}diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rsindex 042385b4..3250871a 100644--- a/packages/wm/src/wm_state.rs+++ b/packages/wm/src/wm_state.rs@@ -9,10 +9,11 @@ use crate::{common::{commands::sync_native_focus,platform::{NativeMonitor, NativeWindow, Platform},+ Direction, Rect,},containers::{commands::{redraw, set_focused_descendant},- traits::CommonGetters,+ traits::{CommonGetters, PositionGetters},Container, RootContainer, WindowContainer,},monitors::{commands::add_monitor, Monitor},@@ -36,7 +37,14 @@ pub struct WmState {pub active_border_window: Option<NativeWindow>,+ /// Name of the most recently focused workspace.+ ///+ /// Used for the `general.toggle_workspace_on_refocus` option on+ /// workspace focus.+ pub recent_workspace_name: Option<String>,+/// Time since a previously focused window was unmanaged or minimized.+ ////// Used to decide whether to override incoming focus events.pub unmanaged_or_minimized_timestamp: Option<Instant>,@@ -54,6 +62,7 @@ impl WmState {containers_to_redraw: Vec::new(),has_pending_focus_sync: false,active_border_window: None,+ recent_workspace_name: None,unmanaged_or_minimized_timestamp: None,binding_modes: Vec::new(),event_tx,@@ -149,9 +158,55 @@ impl WmState {) -> Option<Monitor> {self.monitors()- .iter()- .find(|&m| m.native() == *native_monitor)- .cloned()+ .into_iter()+ .find(|m| m.native() == *native_monitor)+ }++ /// Gets the closest monitor in a given direction.+ ///+ /// Uses i3wm's algorithm for finding best guess.+ pub fn monitor_in_direction(+ &self,+ direction: Direction,+ origin_monitor: &Monitor,+ ) -> anyhow::Result<Option<Monitor>> {+ let origin_rect = origin_monitor.native().rect()?.clone();++ // Create a tuple of monitors and their rect.+ let monitors_with_rect = self+ .monitors()+ .into_iter()+ .map(|monitor| {+ let rect = monitor.native().rect()?.clone();+ anyhow::Ok((monitor, rect))+ })+ .try_collect::<Vec<_>>()?;++ let closest_monitor = monitors_with_rect+ .into_iter()+ .filter(|(_, rect)| match direction {+ Direction::Right => {+ rect.x() > origin_rect.x() && rect.has_overlap_y(&origin_rect)+ }+ Direction::Left => {+ rect.x() < origin_rect.x() && rect.has_overlap_y(&origin_rect)+ }+ Direction::Down => {+ rect.y() > origin_rect.y() && rect.has_overlap_x(&origin_rect)+ }+ Direction::Up => {+ rect.y() < origin_rect.y() && rect.has_overlap_x(&origin_rect)+ }+ })+ .min_by(|(_, rect_a), (_, rect_b)| match direction {+ Direction::Right => rect_a.x().cmp(&rect_b.x()),+ Direction::Left => rect_b.x().cmp(&rect_a.x()),+ Direction::Down => rect_a.y().cmp(&rect_b.y()),+ Direction::Up => rect_b.y().cmp(&rect_a.y()),+ })+ .map(|(monitor, _)| monitor);++ Ok(closest_monitor)}/// Gets window that corresponds to the given `NativeWindow`.@@ -161,9 +216,18 @@ impl WmState {) -> Option<WindowContainer> {self.windows()- .iter()+ .into_iter().find(|w| w.native() == *native_window)- .cloned()+ }++ pub fn workspace_by_name(+ &self,+ workspace_name: &str,+ ) -> Option<Workspace> {+ self+ .workspaces()+ .into_iter()+ .find(|w| w.config().name == workspace_name)}/// Gets windows that should be redrawn.diff --git a/packages/wm/src/workspaces/commands/activate_workspace.rs b/packages/wm/src/workspaces/commands/activate_workspace.rsindex 2205ef00..2f5371e9 100644--- a/packages/wm/src/workspaces/commands/activate_workspace.rs+++ b/packages/wm/src/workspaces/commands/activate_workspace.rs@@ -15,7 +15,7 @@ use crate::{/// If no workspace name is provided, the first suitable workspace defined/// in the user's config will be used.pub fn activate_workspace(- workspace_name: Option<String>,+ workspace_name: Option<&str>,target_monitor: &Monitor,state: &mut WmState,config: &UserConfig,@@ -51,7 +51,7 @@ pub fn activate_workspace(/// Gets config for the workspace to activate.fn workspace_config(- workspace_name: Option<String>,+ workspace_name: Option<&str>,target_monitor: &Monitor,state: &mut WmState,config: &UserConfig,diff --git a/packages/wm/src/workspaces/commands/focus_workspace.rs b/packages/wm/src/workspaces/commands/focus_workspace.rsnew file mode 100644index 00000000..2fd61d69--- /dev/null+++ b/packages/wm/src/workspaces/commands/focus_workspace.rs@@ -0,0 +1,171 @@+use anyhow::Context;+use tracing::info;++use crate::{+ common::Direction,+ containers::{commands::set_focused_descendant, traits::CommonGetters},+ user_config::UserConfig,+ wm_state::WmState,+ workspaces::{+ commands::{activate_workspace, deactivate_workspace},+ Workspace,+ },+};++pub enum FocusWorkspaceTarget {+ Name(String),+ Recent,+ Next,+ Previous,+ Direction(Direction),+}++/// Focuses a workspace by a given target. This target can be a workspace+/// name, the most recently focused workspace, the next workspace, the+/// previous workspace, or the workspace in a given direction from the+/// currently focused workspace.+///+/// The workspace will be activated if it isn't already active.+pub fn focus_workspace(+ target: FocusWorkspaceTarget,+ state: &mut WmState,+ config: &UserConfig,+) -> anyhow::Result<()> {+ let focused_workspace = state+ .focused_container()+ .and_then(|c| c.workspace())+ .context("No workspace is currently focused.")?;++ let workspace_name =+ target_workspace_name(target, &focused_workspace, state, config)?;++ if let Some(workspace_name) = workspace_name {+ // Get the workspace to focus. If it's currently inactive, then+ // activate it on the currently focused monitor.+ let workspace_to_focus =+ match state.workspace_by_name(&workspace_name) {+ Some(workspace) => Some(workspace),+ None => {+ let focused_monitor =+ focused_workspace.monitor().context("No focused monitor.")?;++ activate_workspace(+ Some(&workspace_name),+ &focused_monitor,+ state,+ config,+ )?;++ state.workspace_by_name(&workspace_name)+ }+ }+ .context("Failed to get workspace to focus.")?;++ let displayed_workspace = workspace_to_focus+ .monitor()+ .and_then(|monitor| monitor.displayed_workspace())+ .context("No workspace is currently displayed.")?;++ // Save the currently focused workspace as recent.+ state.recent_workspace_name = Some(focused_workspace.config().name);++ info!(+ "Focusing workspace: '{}'.",+ workspace_to_focus.config().name+ );++ // Set focus to the last focused window in workspace. If the workspace+ // has no descendant windows, then set focus to the workspace itself.+ let container_to_focus = workspace_to_focus+ .last_focused_descendant()+ .unwrap_or_else(|| workspace_to_focus.clone().into());++ set_focused_descendant(container_to_focus, None);+ state.has_pending_focus_sync = true;++ // Display the workspace to switch focus to.+ state.containers_to_redraw.push(displayed_workspace.into());+ state.containers_to_redraw.push(workspace_to_focus.into());++ // Get empty workspace to destroy (if one is found). Cannot destroy empty+ // workspaces if they're the only workspace on the monitor.+ let workspace_to_destroy =+ state.workspaces().into_iter().find(|workspace| {+ !workspace.config().keep_alive+ && !workspace.has_children()+ && !workspace.is_displayed()+ });++ if let Some(workspace) = workspace_to_destroy {+ deactivate_workspace(workspace, state)?;+ }+ }+ Ok(())+}++/// Gets the name of the workspace to focus.+fn target_workspace_name(+ target: FocusWorkspaceTarget,+ focused_workspace: &Workspace,+ state: &WmState,+ config: &UserConfig,+) -> anyhow::Result<Option<String>> {+ let workspace_configs = &config.value.workspaces;+ let mut workspaces = state.workspaces();++ // Sort workspaces by their position in the user config.+ workspaces.sort_by_key(|workspace| {+ workspace_configs+ .iter()+ .position(|config| config.name == workspace.config().name)+ });++ // Get index of the currently focused workspace within the sorted vector+ // of workspaces.+ let focused_index = workspaces+ .iter()+ .position(|workspace| workspace.id() == focused_workspace.id())+ .context("Unable to get config position of focused workspace.")?;++ let workspace_name = match target {+ FocusWorkspaceTarget::Name(name) => {+ match focused_workspace.config().name == name {+ false => Some(name),+ true if config.value.general.toggle_workspace_on_refocus => {+ state.recent_workspace_name.clone()+ }+ true => None,+ }+ }+ FocusWorkspaceTarget::Recent => state.recent_workspace_name.clone(),+ FocusWorkspaceTarget::Next => {+ let index = match focused_index == workspaces.len() - 1 {+ true => 0,+ _ => focused_index + 1,+ };++ workspaces.get(index).map(|w| w.config().name.clone())+ }+ FocusWorkspaceTarget::Previous => {+ let index = match focused_index {+ 0 => workspaces.len() - 1,+ _ => focused_index - 1,+ };++ workspaces.get(index).map(|w| w.config().name.clone())+ }+ FocusWorkspaceTarget::Direction(direction) => {+ let focused_monitor =+ focused_workspace.monitor().context("No focused monitor.")?;++ let monitor =+ state.monitor_in_direction(direction, &focused_monitor)?;++ monitor+ .and_then(|m| m.displayed_workspace())+ .map(|w| w.config().name.clone())+ }+ };++ Ok(workspace_name)+}diff --git a/packages/wm/src/workspaces/commands/mod.rs b/packages/wm/src/workspaces/commands/mod.rsindex b971c131..0705abc3 100644--- a/packages/wm/src/workspaces/commands/mod.rs+++ b/packages/wm/src/workspaces/commands/mod.rs@@ -1,5 +1,7 @@mod activate_workspace;mod deactivate_workspace;+mod focus_workspace;pub use activate_workspace::*;pub use deactivate_workspace::*;+pub use focus_workspace::*;