diff --git a/niri-config/src/lib.rs b/niri-config/src/lib.rs index be93f9a7..355007f6 100644 --- a/niri-config/src/lib.rs +++ b/niri-config/src/lib.rs @@ -11,7 +11,7 @@ use bitflags::bitflags; use knuffel::errors::DecodeError; use knuffel::Decode as _; use miette::{miette, Context, IntoDiagnostic, NarratableReportHandler}; -use niri_ipc::{ConfiguredMode, LayoutSwitchTarget, SizeChange, Transform}; +use niri_ipc::{ConfiguredMode, LayoutSwitchTarget, SizeChange, Transform, WorkspaceReferenceArg}; use regex::Regex; use smithay::input::keyboard::keysyms::KEY_NoSymbol; use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE}; @@ -52,6 +52,8 @@ pub struct Config { pub binds: Binds, #[knuffel(child, default)] pub debug: DebugConfig, + #[knuffel(children(name = "workspace"))] + pub workspaces: Vec, } // FIXME: Add other devices. @@ -693,6 +695,17 @@ pub struct EnvironmentVariable { pub value: Option, } +#[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)] +pub struct Workspace { + #[knuffel(argument)] + pub name: WorkspaceName, + #[knuffel(child, unwrap(argument))] + pub open_on_output: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WorkspaceName(pub String); + #[derive(knuffel::Decode, Debug, Default, Clone, PartialEq)] pub struct WindowRule { #[knuffel(children(name = "match"))] @@ -706,6 +719,8 @@ pub struct WindowRule { #[knuffel(child, unwrap(argument))] pub open_on_output: Option, #[knuffel(child, unwrap(argument))] + pub open_on_workspace: Option, + #[knuffel(child, unwrap(argument))] pub open_maximized: Option, #[knuffel(child, unwrap(argument))] pub open_fullscreen: Option, @@ -890,14 +905,14 @@ pub enum Action { CenterColumn, FocusWorkspaceDown, FocusWorkspaceUp, - FocusWorkspace(#[knuffel(argument)] u8), + FocusWorkspace(#[knuffel(argument)] WorkspaceReference), FocusWorkspacePrevious, MoveWindowToWorkspaceDown, MoveWindowToWorkspaceUp, - MoveWindowToWorkspace(#[knuffel(argument)] u8), + MoveWindowToWorkspace(#[knuffel(argument)] WorkspaceReference), MoveColumnToWorkspaceDown, MoveColumnToWorkspaceUp, - MoveColumnToWorkspace(#[knuffel(argument)] u8), + MoveColumnToWorkspace(#[knuffel(argument)] WorkspaceReference), MoveWorkspaceDown, MoveWorkspaceUp, FocusMonitorLeft, @@ -962,14 +977,20 @@ impl From for Action { niri_ipc::Action::CenterColumn => Self::CenterColumn, niri_ipc::Action::FocusWorkspaceDown => Self::FocusWorkspaceDown, niri_ipc::Action::FocusWorkspaceUp => Self::FocusWorkspaceUp, - niri_ipc::Action::FocusWorkspace { index } => Self::FocusWorkspace(index), + niri_ipc::Action::FocusWorkspace { reference } => { + Self::FocusWorkspace(WorkspaceReference::from(reference)) + } niri_ipc::Action::FocusWorkspacePrevious => Self::FocusWorkspacePrevious, niri_ipc::Action::MoveWindowToWorkspaceDown => Self::MoveWindowToWorkspaceDown, niri_ipc::Action::MoveWindowToWorkspaceUp => Self::MoveWindowToWorkspaceUp, - niri_ipc::Action::MoveWindowToWorkspace { index } => Self::MoveWindowToWorkspace(index), + niri_ipc::Action::MoveWindowToWorkspace { reference } => { + Self::MoveWindowToWorkspace(WorkspaceReference::from(reference)) + } niri_ipc::Action::MoveColumnToWorkspaceDown => Self::MoveColumnToWorkspaceDown, niri_ipc::Action::MoveColumnToWorkspaceUp => Self::MoveColumnToWorkspaceUp, - niri_ipc::Action::MoveColumnToWorkspace { index } => Self::MoveColumnToWorkspace(index), + niri_ipc::Action::MoveColumnToWorkspace { reference } => { + Self::MoveColumnToWorkspace(WorkspaceReference::from(reference)) + } niri_ipc::Action::MoveWorkspaceDown => Self::MoveWorkspaceDown, niri_ipc::Action::MoveWorkspaceUp => Self::MoveWorkspaceUp, niri_ipc::Action::FocusMonitorLeft => Self::FocusMonitorLeft, @@ -1002,6 +1023,59 @@ impl From for Action { } } +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum WorkspaceReference { + Index(u8), + Name(String), +} + +impl From for WorkspaceReference { + fn from(reference: WorkspaceReferenceArg) -> WorkspaceReference { + match reference { + WorkspaceReferenceArg::Index(i) => Self::Index(i), + WorkspaceReferenceArg::Name(n) => Self::Name(n), + } + } +} + +impl knuffel::DecodeScalar for WorkspaceReference { + fn type_check( + type_name: &Option>, + ctx: &mut knuffel::decode::Context, + ) { + if let Some(type_name) = &type_name { + ctx.emit_error(DecodeError::unexpected( + type_name, + "type name", + "no type name expected for this node", + )); + } + } + + fn raw_decode( + val: &knuffel::span::Spanned, + ctx: &mut knuffel::decode::Context, + ) -> Result> { + match &**val { + knuffel::ast::Literal::String(ref s) => Ok(WorkspaceReference::Name(s.clone().into())), + knuffel::ast::Literal::Int(ref value) => match value.try_into() { + Ok(v) => Ok(WorkspaceReference::Index(v)), + Err(e) => { + ctx.emit_error(DecodeError::conversion(val, e)); + Ok(WorkspaceReference::Index(0)) + } + }, + _ => { + ctx.emit_error(DecodeError::unsupported( + val, + "Unsupported value, only numbers and strings are recognized", + )); + Ok(WorkspaceReference::Index(0)) + } + } + } +} + #[derive(knuffel::Decode, Debug, Default, PartialEq)] pub struct DebugConfig { #[knuffel(child, unwrap(argument))] @@ -1409,6 +1483,54 @@ where } } +impl knuffel::DecodeScalar for WorkspaceName { + fn type_check( + type_name: &Option>, + ctx: &mut knuffel::decode::Context, + ) { + if let Some(type_name) = &type_name { + ctx.emit_error(DecodeError::unexpected( + type_name, + "type name", + "no type name expected for this node", + )); + } + } + + fn raw_decode( + val: &knuffel::span::Spanned, + ctx: &mut knuffel::decode::Context, + ) -> Result> { + #[derive(Debug)] + struct WorkspaceNameSet(HashSet); + match &**val { + knuffel::ast::Literal::String(ref s) => { + let mut name_set: HashSet = match ctx.get::() { + Some(h) => h.0.clone(), + None => HashSet::new(), + }; + if !name_set.insert(s.clone().to_string()) { + ctx.emit_error(DecodeError::unexpected( + val, + "named workspace", + format!("duplicate named workspace: {}", s), + )); + return Ok(Self(String::new())); + } + ctx.set(WorkspaceNameSet(name_set)); + Ok(Self(s.clone().into())) + } + _ => { + ctx.emit_error(DecodeError::unsupported( + val, + "workspace names must be strings", + )); + Ok(Self(String::new())) + } + } + } +} + impl knuffel::Decode for WindowOpenAnim where S: knuffel::traits::ErrorSpan, @@ -2278,6 +2400,7 @@ mod tests { Mod+Ctrl+Shift+L { move-window-to-monitor-right; } Mod+Comma { consume-window-into-column; } Mod+1 { focus-workspace 1; } + Mod+Shift+1 { focus-workspace "workspace-1"; } Mod+Shift+E { quit skip-confirmation=true; } Mod+WheelScrollDown cooldown-ms=150 { focus-workspace-down; } } @@ -2285,6 +2408,12 @@ mod tests { debug { render-drm-device "/dev/dri/renderD129" } + + workspace "workspace-1" { + open-on-output "eDP-1" + } + workspace "workspace-2" + workspace "workspace-3" "##, Config { input: Input { @@ -2489,6 +2618,20 @@ mod tests { }, ..Default::default() }], + workspaces: vec![ + Workspace { + name: WorkspaceName("workspace-1".to_string()), + open_on_output: Some("eDP-1".to_string()), + }, + Workspace { + name: WorkspaceName("workspace-2".to_string()), + open_on_output: None, + }, + Workspace { + name: WorkspaceName("workspace-3".to_string()), + open_on_output: None, + }, + ], binds: Binds(vec![ Bind { key: Key { @@ -2540,7 +2683,18 @@ mod tests { trigger: Trigger::Keysym(Keysym::_1), modifiers: Modifiers::COMPOSITOR, }, - action: Action::FocusWorkspace(1), + action: Action::FocusWorkspace(WorkspaceReference::Index(1)), + cooldown: None, + allow_when_locked: false, + }, + Bind { + key: Key { + trigger: Trigger::Keysym(Keysym::_1), + modifiers: Modifiers::COMPOSITOR | Modifiers::SHIFT, + }, + action: Action::FocusWorkspace(WorkspaceReference::Name( + "workspace-1".to_string(), + )), cooldown: None, allow_when_locked: false, }, diff --git a/niri-ipc/src/lib.rs b/niri-ipc/src/lib.rs index beabfcbc..b0f124f9 100644 --- a/niri-ipc/src/lib.rs +++ b/niri-ipc/src/lib.rs @@ -146,11 +146,11 @@ pub enum Action { FocusWorkspaceDown, /// Focus the workspace above. FocusWorkspaceUp, - /// Focus a workspace by index. + /// Focus a workspace by reference (index or name). FocusWorkspace { - /// Index of the workspace to focus. + /// Reference (index or name) of the workspace to focus. #[cfg_attr(feature = "clap", arg())] - index: u8, + reference: WorkspaceReferenceArg, }, /// Focus the previous workspace. FocusWorkspacePrevious, @@ -158,21 +158,21 @@ pub enum Action { MoveWindowToWorkspaceDown, /// Move the focused window to the workspace above. MoveWindowToWorkspaceUp, - /// Move the focused window to a workspace by index. + /// Move the focused window to a workspace by reference (index or name). MoveWindowToWorkspace { - /// Index of the target workspace. + /// Reference (index or name) of the workspace to move the window to. #[cfg_attr(feature = "clap", arg())] - index: u8, + reference: WorkspaceReferenceArg, }, /// Move the focused column to the workspace below. MoveColumnToWorkspaceDown, /// Move the focused column to the workspace above. MoveColumnToWorkspaceUp, - /// Move the focused column to a workspace by index. + /// Move the focused column to a workspace by reference (index or name). MoveColumnToWorkspace { - /// Index of the target workspace. + /// Reference (index or name) of the workspace to move the column to. #[cfg_attr(feature = "clap", arg())] - index: u8, + reference: WorkspaceReferenceArg, }, /// Move the focused workspace down. MoveWorkspaceDown, @@ -257,6 +257,15 @@ pub enum SizeChange { AdjustProportion(f64), } +/// Workspace reference (index or name) to operate on. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +pub enum WorkspaceReferenceArg { + /// Index of the workspace. + Index(u8), + /// Name of the workspace. + Name(String), +} + /// Layout to switch to. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] pub enum LayoutSwitchTarget { @@ -475,6 +484,24 @@ pub enum OutputConfigChanged { OutputWasMissing, } +impl FromStr for WorkspaceReferenceArg { + type Err = &'static str; + + fn from_str(s: &str) -> Result { + let reference = if let Ok(index) = s.parse::() { + if let Ok(idx) = u8::try_from(index) { + Self::Index(idx) + } else { + return Err("workspace indexes must be between 0 and 255"); + } + } else { + Self::Name(s.to_string()) + }; + + Ok(reference) + } +} + impl FromStr for SizeChange { type Err = &'static str; diff --git a/src/handlers/compositor.rs b/src/handlers/compositor.rs index 7d3f0419..2afb8fe8 100644 --- a/src/handlers/compositor.rs +++ b/src/handlers/compositor.rs @@ -119,22 +119,27 @@ impl CompositorHandler for State { let toplevel = window.toplevel().expect("no X11 support"); - let (rules, width, is_full_width, output) = + let (rules, width, is_full_width, output, workspace_name) = if let InitialConfigureState::Configured { rules, width, is_full_width, output, + workspace_name, } = state { // Check that the output is still connected. let output = output.filter(|o| self.niri.layout.monitor_for_output(o).is_some()); - (rules, width, is_full_width, output) + // Chech that the workspace still exists. + let workspace_name = workspace_name + .filter(|n| self.niri.layout.find_workspace_by_name(n).is_some()); + + (rules, width, is_full_width, output, workspace_name) } else { error!("window map must happen after initial configure"); - (ResolvedWindowRules::empty(), None, false, None) + (ResolvedWindowRules::empty(), None, false, None, None) }; let parent = toplevel @@ -160,6 +165,13 @@ impl CompositorHandler for State { self.niri .layout .add_window_right_of(&p, mapped, width, is_full_width) + } else if let Some(workspace_name) = &workspace_name { + self.niri.layout.add_window_to_named_workspace( + workspace_name, + mapped, + width, + is_full_width, + ) } else if let Some(output) = &output { self.niri .layout diff --git a/src/handlers/xdg_shell.rs b/src/handlers/xdg_shell.rs index 44f07839..30df1d5f 100644 --- a/src/handlers/xdg_shell.rs +++ b/src/handlers/xdg_shell.rs @@ -369,38 +369,52 @@ impl XdgShellHandler for State { width, is_full_width, output, + workspace_name, } => { // Figure out the monitor following a similar logic to initial configure. // FIXME: deduplicate. - let mon = output - .as_ref() - .and_then(|o| self.niri.layout.monitor_for_output(o)) - .map(|mon| (mon, false)) - // If not, check if we have a parent with a monitor. - .or_else(|| { - toplevel - .parent() - .and_then(|parent| self.niri.layout.find_window_and_output(&parent)) - .map(|(_win, output)| output) - .and_then(|o| self.niri.layout.monitor_for_output(o)) - .map(|mon| (mon, true)) - }) - // If not, fall back to the active monitor. - .or_else(|| { - self.niri - .layout - .active_monitor_ref() - .map(|mon| (mon, false)) - }); + let mon = workspace_name + .as_deref() + .and_then(|name| self.niri.layout.monitor_for_workspace(name)) + .map(|mon| (mon, false)); + + let mon = mon.or_else(|| { + output + .as_ref() + .and_then(|o| self.niri.layout.monitor_for_output(o)) + .map(|mon| (mon, false)) + // If not, check if we have a parent with a monitor. + .or_else(|| { + toplevel + .parent() + .and_then(|parent| { + self.niri.layout.find_window_and_output(&parent) + }) + .map(|(_win, output)| output) + .and_then(|o| self.niri.layout.monitor_for_output(o)) + .map(|mon| (mon, true)) + }) + // If not, fall back to the active monitor. + .or_else(|| { + self.niri + .layout + .active_monitor_ref() + .map(|mon| (mon, false)) + }) + }); *output = mon .filter(|(_, parent)| !parent) .map(|(mon, _)| mon.output.clone()); let mon = mon.map(|(mon, _)| mon); - let ws = mon - .map(|mon| mon.active_workspace_ref()) - .or_else(|| self.niri.layout.active_workspace()); + let ws = workspace_name + .as_deref() + .and_then(|name| mon.map(|mon| mon.find_named_workspace(name))) + .unwrap_or_else(|| { + mon.map(|mon| mon.active_workspace_ref()) + .or_else(|| self.niri.layout.active_workspace()) + }); if let Some(ws) = ws { toplevel.with_pending_state(|state| { @@ -577,12 +591,20 @@ impl State { return; }; - // Pick the target monitor. First, check if we had an output set in the window rules. + // Pick the target monitor. First, check if we had a workspace set in the window rules. let mon = rules - .open_on_output + .open_on_workspace .as_deref() - .and_then(|name| self.niri.output_by_name.get(name)) - .and_then(|o| self.niri.layout.monitor_for_output(o)); + .and_then(|name| self.niri.layout.monitor_for_workspace(name)); + + // If not, check if we had an output set in the window rules. + let mon = mon.or_else(|| { + rules + .open_on_output + .as_deref() + .and_then(|name| self.niri.output_by_name.get(name)) + .and_then(|o| self.niri.layout.monitor_for_output(o)) + }); // If not, check if the window requested one for fullscreen. let mon = mon.or_else(|| { @@ -622,9 +644,14 @@ impl State { let is_full_width = rules.open_maximized.unwrap_or(false); // Tell the surface the preferred size and bounds for its likely output. - let ws = mon - .map(|mon| mon.active_workspace_ref()) - .or_else(|| self.niri.layout.active_workspace()); + let ws = rules + .open_on_workspace + .as_deref() + .and_then(|name| mon.map(|mon| mon.find_named_workspace(name))) + .unwrap_or_else(|| { + mon.map(|mon| mon.active_workspace_ref()) + .or_else(|| self.niri.layout.active_workspace()) + }); if let Some(ws) = ws { // Set a fullscreen state based on window request and window rule. @@ -663,6 +690,7 @@ impl State { width, is_full_width, output, + workspace_name: ws.and_then(|w| w.name.clone()), }; toplevel.send_configure(); diff --git a/src/input/mod.rs b/src/input/mod.rs index 8206890c..1984b23c 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -587,12 +587,22 @@ impl State { // FIXME: granular self.niri.queue_redraw_all(); } - Action::MoveWindowToWorkspace(idx) => { - let idx = idx.saturating_sub(1) as usize; - self.niri.layout.move_to_workspace(idx); - self.maybe_warp_cursor_to_focus(); - // FIXME: granular - self.niri.queue_redraw_all(); + Action::MoveWindowToWorkspace(reference) => { + if let Some((output, index)) = self.niri.find_output_and_workspace_index(reference) + { + if let Some(output) = output { + self.niri.layout.move_to_workspace_on_output(&output, index); + if !self.maybe_warp_cursor_to_focus_centered() { + self.move_cursor_to_output(&output); + } + } else { + self.niri.layout.move_to_workspace(index); + self.maybe_warp_cursor_to_focus(); + } + + // FIXME: granular + self.niri.queue_redraw_all(); + } } Action::MoveColumnToWorkspaceDown => { self.niri.layout.move_column_to_workspace_down(); @@ -606,12 +616,24 @@ impl State { // FIXME: granular self.niri.queue_redraw_all(); } - Action::MoveColumnToWorkspace(idx) => { - let idx = idx.saturating_sub(1) as usize; - self.niri.layout.move_column_to_workspace(idx); - self.maybe_warp_cursor_to_focus(); - // FIXME: granular - self.niri.queue_redraw_all(); + Action::MoveColumnToWorkspace(reference) => { + if let Some((output, index)) = self.niri.find_output_and_workspace_index(reference) + { + if let Some(output) = output { + self.niri + .layout + .move_column_to_workspace_on_output(&output, index); + if !self.maybe_warp_cursor_to_focus_centered() { + self.move_cursor_to_output(&output); + } + } else { + self.niri.layout.move_column_to_workspace(index); + self.maybe_warp_cursor_to_focus(); + } + + // FIXME: granular + self.niri.queue_redraw_all(); + } } Action::FocusWorkspaceDown => { self.niri.layout.switch_workspace_down(); @@ -625,19 +647,28 @@ impl State { // FIXME: granular self.niri.queue_redraw_all(); } - Action::FocusWorkspace(idx) => { - let idx = idx.saturating_sub(1) as usize; + Action::FocusWorkspace(reference) => { + if let Some((output, index)) = self.niri.find_output_and_workspace_index(reference) + { + if let Some(output) = output { + self.niri.layout.focus_output(&output); + self.niri.layout.switch_workspace(index); + if !self.maybe_warp_cursor_to_focus_centered() { + self.move_cursor_to_output(&output); + } + } else { + let config = &self.niri.config; + if config.borrow().input.workspace_auto_back_and_forth { + self.niri.layout.switch_workspace_auto_back_and_forth(index); + } else { + self.niri.layout.switch_workspace(index); + } + self.maybe_warp_cursor_to_focus(); + } - let config = &self.niri.config; - if config.borrow().input.workspace_auto_back_and_forth { - self.niri.layout.switch_workspace_auto_back_and_forth(idx); - } else { - self.niri.layout.switch_workspace(idx); + // FIXME: granular + self.niri.queue_redraw_all(); } - - self.maybe_warp_cursor_to_focus(); - // FIXME: granular - self.niri.queue_redraw_all(); } Action::FocusWorkspacePrevious => { self.niri.layout.switch_workspace_previous(); diff --git a/src/layout/mod.rs b/src/layout/mod.rs index d091c024..0eb451e6 100644 --- a/src/layout/mod.rs +++ b/src/layout/mod.rs @@ -34,7 +34,7 @@ use std::mem; use std::rc::Rc; use std::time::Duration; -use niri_config::{CenterFocusedColumn, Config, Struts}; +use niri_config::{CenterFocusedColumn, Config, Struts, Workspace as WorkspaceConfig}; use niri_ipc::SizeChange; use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement}; use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement; @@ -279,7 +279,7 @@ impl Options { impl Layout { pub fn new(config: &Config) -> Self { - Self::with_options(Options::from_config(config)) + Self::with_options_and_workspaces(config, Options::from_config(config)) } pub fn with_options(options: Options) -> Self { @@ -289,6 +289,21 @@ impl Layout { } } + fn with_options_and_workspaces(config: &Config, options: Options) -> Self { + let opts = Rc::new(options); + + let workspaces = config + .workspaces + .iter() + .map(|ws| Workspace::new_with_config_no_outputs(Some(ws.clone()), opts.clone())) + .collect(); + + Self { + monitor_set: MonitorSet::NoOutputs { workspaces }, + options: opts, + } + } + pub fn add_output(&mut self, output: Output) { let id = OutputId::new(&output); @@ -318,7 +333,7 @@ impl Layout { // The user could've closed a window while remaining on this workspace, on // another monitor. However, we will add an empty workspace in the end // instead. - if ws.has_windows() { + if ws.has_windows() || ws.name.is_some() { workspaces.push(ws); } @@ -463,6 +478,67 @@ impl Layout { } } + /// Adds a new window to the layout on a specific workspace. + pub fn add_window_to_named_workspace( + &mut self, + workspace_name: &str, + window: W, + width: Option, + is_full_width: bool, + ) -> Option<&Output> { + let mut width = width.unwrap_or_else(|| ColumnWidth::Fixed(window.size().w)); + if let ColumnWidth::Fixed(w) = &mut width { + let rules = window.rules(); + let border_config = rules.border.resolve_against(self.options.border); + if !border_config.off { + *w += border_config.width as i32 * 2; + } + } + + match &mut self.monitor_set { + MonitorSet::Normal { + monitors, + active_monitor_idx, + .. + } => { + let (mon_idx, mon, ws_idx) = monitors + .iter_mut() + .enumerate() + .find_map(|(mon_idx, mon)| { + mon.find_named_workspace_index(workspace_name) + .map(move |ws_idx| (mon_idx, mon, ws_idx)) + }) + .unwrap(); + + // Don't steal focus from an active fullscreen window. + let mut activate = true; + let ws = &mon.workspaces[ws_idx]; + if mon_idx == *active_monitor_idx + && !ws.columns.is_empty() + && ws.columns[ws.active_column_idx].is_fullscreen + { + activate = false; + } + + // Don't activate if on a different workspace. + if mon.active_workspace_idx != ws_idx { + activate = false; + } + + mon.add_window(ws_idx, window, activate, width, is_full_width); + Some(&mon.output) + } + MonitorSet::NoOutputs { workspaces } => { + let ws = workspaces + .iter_mut() + .find(|ws| ws.name.as_deref() == Some(workspace_name)) + .unwrap(); + ws.add_window(window, true, width, is_full_width); + None + } + } + } + pub fn add_column_by_idx( &mut self, monitor_idx: usize, @@ -649,6 +725,7 @@ impl Layout { && idx != mon.active_workspace_idx && idx != mon.workspaces.len() - 1 && mon.workspace_switch.is_none() + && mon.workspaces[idx].name.is_none() { mon.workspaces.remove(idx); @@ -668,7 +745,7 @@ impl Layout { rv = Some(ws.remove_window(window)); // Clean up empty workspaces. - if !ws.has_windows() { + if !ws.has_windows() && workspaces[idx].name.is_none() { workspaces.remove(idx); } @@ -718,6 +795,63 @@ impl Layout { None } + pub fn find_workspace_by_name(&self, workspace_name: &str) -> Option<(usize, &Workspace)> { + match &self.monitor_set { + MonitorSet::Normal { ref monitors, .. } => { + for mon in monitors { + if let Some((index, workspace)) = mon + .workspaces + .iter() + .enumerate() + .find(|(_, w)| w.name.as_deref() == Some(workspace_name)) + { + return Some((index, workspace)); + } + } + } + MonitorSet::NoOutputs { workspaces } => { + if let Some((index, workspace)) = workspaces + .iter() + .enumerate() + .find(|(_, w)| w.name.as_deref() == Some(workspace_name)) + { + return Some((index, workspace)); + } + } + } + + None + } + + pub fn unname_workspace(&mut self, workspace_name: &str) { + match &mut self.monitor_set { + MonitorSet::Normal { monitors, .. } => { + for mon in monitors { + if mon.unname_workspace(workspace_name) { + if mon.workspace_switch.is_none() { + mon.clean_up_workspaces(); + } + return; + } + } + } + MonitorSet::NoOutputs { workspaces } => { + for (idx, ws) in workspaces.iter_mut().enumerate() { + if ws.name.as_deref() == Some(workspace_name) { + ws.unname(); + + // Clean up empty workspaces. + if !ws.has_windows() { + workspaces.remove(idx); + } + + return; + } + } + } + } + } + pub fn find_window_and_output_mut( &mut self, wl_surface: &WlSurface, @@ -970,6 +1104,19 @@ impl Layout { monitors.iter().find(|monitor| &monitor.output == output) } + pub fn monitor_for_workspace(&self, workspace_name: &str) -> Option<&Monitor> { + let MonitorSet::Normal { monitors, .. } = &self.monitor_set else { + return None; + }; + + monitors.iter().find(|monitor| { + monitor + .workspaces + .iter() + .any(|ws| ws.name.as_deref() == Some(workspace_name)) + }) + } + pub fn outputs(&self) -> impl Iterator + '_ { let monitors = if let MonitorSet::Normal { monitors, .. } = &self.monitor_set { &monitors[..] @@ -1127,6 +1274,12 @@ impl Layout { monitor.move_to_workspace(idx); } + pub fn move_to_workspace_on_output(&mut self, output: &Output, idx: usize) { + self.move_to_output(output); + self.focus_output(output); + self.move_to_workspace(idx); + } + pub fn move_column_to_workspace_up(&mut self) { let Some(monitor) = self.active_monitor() else { return; @@ -1148,6 +1301,12 @@ impl Layout { monitor.move_column_to_workspace(idx); } + pub fn move_column_to_workspace_on_output(&mut self, output: &Output, idx: usize) { + self.move_to_output(output); + self.focus_output(output); + self.move_column_to_workspace(idx); + } + pub fn switch_workspace_up(&mut self) { let Some(monitor) = self.active_monitor() else { return; @@ -1257,6 +1416,7 @@ impl Layout { use crate::layout::monitor::WorkspaceSwitch; let mut seen_workspace_id = HashSet::new(); + let mut seen_workspace_name = HashSet::new(); let (monitors, &primary_idx, &active_monitor_idx) = match &self.monitor_set { MonitorSet::Normal { @@ -1267,8 +1427,8 @@ impl Layout { MonitorSet::NoOutputs { workspaces } => { for workspace in workspaces { assert!( - workspace.has_windows(), - "with no outputs there cannot be empty workspaces" + workspace.has_windows() || workspace.name.is_some(), + "with no outputs there cannot be empty unnamed workspaces" ); assert_eq!( @@ -1281,6 +1441,13 @@ impl Layout { "workspace id must be unique" ); + if let Some(name) = &workspace.name { + assert!( + seen_workspace_name.insert(name), + "workspace name must be unique" + ); + } + workspace.verify_invariants(); } @@ -1343,14 +1510,19 @@ impl Layout { "monitor must have an empty workspace in the end" ); + assert!( + monitor.workspaces.last().unwrap().name.is_none(), + "monitor must have an unnamed workspace in the end" + ); + // If there's no workspace switch in progress, there can't be any non-last non-active // empty workspaces. if monitor.workspace_switch.is_none() { for (idx, ws) in monitor.workspaces.iter().enumerate().rev().skip(1) { if idx != monitor.active_workspace_idx { assert!( - !ws.columns.is_empty(), - "non-active workspace can't be empty except the last one" + !ws.columns.is_empty() || ws.name.is_some(), + "non-active workspace can't be empty and unnamed except the last one" ); } } @@ -1370,6 +1542,13 @@ impl Layout { "workspace id must be unique" ); + if let Some(name) = &workspace.name { + assert!( + seen_workspace_name.insert(name), + "workspace name must be unique" + ); + } + workspace.verify_invariants(); } } @@ -1448,6 +1627,48 @@ impl Layout { } } + pub fn ensure_named_workspace(&mut self, ws_config: &WorkspaceConfig) { + if self.find_workspace_by_name(&ws_config.name.0).is_some() { + return; + } + + let options = self.options.clone(); + + match &mut self.monitor_set { + MonitorSet::Normal { + monitors, + primary_idx, + active_monitor_idx, + } => { + let mon_idx = ws_config + .open_on_output + .as_deref() + .map(|name| { + monitors + .iter_mut() + .position(|monitor| monitor.output.name().eq_ignore_ascii_case(name)) + .unwrap_or(*primary_idx) + }) + .unwrap_or(*active_monitor_idx); + let mon = &mut monitors[mon_idx]; + + let ws = Workspace::new_with_config( + mon.output.clone(), + Some(ws_config.clone()), + options, + ); + mon.workspaces.insert(0, ws); + mon.active_workspace_idx += 1; + mon.workspace_switch = None; + mon.clean_up_workspaces(); + } + MonitorSet::NoOutputs { workspaces } => { + let ws = Workspace::new_with_config_no_outputs(Some(ws_config.clone()), options); + workspaces.insert(0, ws); + } + } + } + pub fn update_config(&mut self, config: &Config) { let options = Rc::new(Options::from_config(config)); @@ -2053,6 +2274,7 @@ impl Default for MonitorSet { mod tests { use std::cell::Cell; + use niri_config::WorkspaceName; use proptest::prelude::*; use proptest_derive::Arbitrary; use smithay::output::{Mode, PhysicalProperties, Subpixel}; @@ -2284,6 +2506,16 @@ mod tests { AddOutput(#[proptest(strategy = "1..=5usize")] usize), RemoveOutput(#[proptest(strategy = "1..=5usize")] usize), FocusOutput(#[proptest(strategy = "1..=5usize")] usize), + AddNamedWorkspace { + #[proptest(strategy = "1..=5usize")] + ws_name: usize, + #[proptest(strategy = "prop::option::of(1..=5usize)")] + output_name: Option, + }, + UnnameWorkspace { + #[proptest(strategy = "1..=5usize")] + ws_name: usize, + }, AddWindow { #[proptest(strategy = "1..=5usize")] id: usize, @@ -2302,6 +2534,16 @@ mod tests { #[proptest(strategy = "arbitrary_min_max_size()")] min_max_size: (Size, Size), }, + AddWindowToNamedWorkspace { + #[proptest(strategy = "1..=5usize")] + id: usize, + #[proptest(strategy = "1..=5usize")] + ws_name: usize, + #[proptest(strategy = "arbitrary_bbox()")] + bbox: Rectangle, + #[proptest(strategy = "arbitrary_min_max_size()")] + min_max_size: (Size, Size), + }, CloseWindow(#[proptest(strategy = "1..=5usize")] usize), FullscreenWindow(#[proptest(strategy = "1..=5usize")] usize), FocusColumnLeft, @@ -2438,6 +2680,18 @@ mod tests { layout.focus_output(&output); } + Op::AddNamedWorkspace { + ws_name, + output_name, + } => { + layout.ensure_named_workspace(&WorkspaceConfig { + name: WorkspaceName(format!("ws{ws_name}")), + open_on_output: output_name.map(|name| format!("output{name}")), + }); + } + Op::UnnameWorkspace { ws_name } => { + layout.unname_workspace(&format!("ws{ws_name}")); + } Op::AddWindow { id, bbox, @@ -2515,6 +2769,53 @@ mod tests { let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1); layout.add_window_right_of(&right_of_id, win, None, false); } + Op::AddWindowToNamedWorkspace { + id, + ws_name, + bbox, + min_max_size, + } => { + let ws_name = format!("ws{ws_name}"); + let mut found_workspace = false; + + match &mut layout.monitor_set { + MonitorSet::Normal { monitors, .. } => { + for mon in monitors { + for ws in &mut mon.workspaces { + for win in ws.windows() { + if win.0.id == id { + return; + } + } + + if ws.name.as_deref() == Some(&ws_name) { + found_workspace = true; + } + } + } + } + MonitorSet::NoOutputs { workspaces, .. } => { + for ws in workspaces { + for win in ws.windows() { + if win.0.id == id { + return; + } + } + + if ws.name.as_deref() == Some(&ws_name) { + found_workspace = true; + } + } + } + } + + if !found_workspace { + return; + } + + let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1); + layout.add_window_to_named_workspace(&ws_name, win, None, false); + } Op::CloseWindow(id) => { layout.remove_window(&id); } @@ -2702,6 +3003,11 @@ mod tests { Op::FocusOutput(0), Op::FocusOutput(1), Op::FocusOutput(2), + Op::AddNamedWorkspace { + ws_name: 1, + output_name: Some(1), + }, + Op::UnnameWorkspace { ws_name: 1 }, Op::AddWindow { id: 0, bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)), @@ -2712,20 +3018,15 @@ mod tests { bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)), min_max_size: Default::default(), }, - Op::AddWindow { + Op::AddWindowRightOf { id: 2, + right_of_id: 1, bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)), min_max_size: Default::default(), }, - Op::AddWindowRightOf { + Op::AddWindowToNamedWorkspace { id: 3, - right_of_id: 0, - bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)), - min_max_size: Default::default(), - }, - Op::AddWindowRightOf { - id: 4, - right_of_id: 1, + ws_name: 1, bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)), min_max_size: Default::default(), }, @@ -2750,17 +3051,14 @@ mod tests { Op::FocusWorkspaceUp, Op::FocusWorkspace(1), Op::FocusWorkspace(2), - Op::FocusWorkspace(3), Op::MoveWindowToWorkspaceDown, Op::MoveWindowToWorkspaceUp, Op::MoveWindowToWorkspace(1), Op::MoveWindowToWorkspace(2), - Op::MoveWindowToWorkspace(3), Op::MoveColumnToWorkspaceDown, Op::MoveColumnToWorkspaceUp, Op::MoveColumnToWorkspace(1), Op::MoveColumnToWorkspace(2), - Op::MoveColumnToWorkspace(3), Op::MoveWindowDown, Op::MoveWindowDownOrToWorkspaceDown, Op::MoveWindowUp, @@ -2847,6 +3145,11 @@ mod tests { Op::FocusOutput(0), Op::FocusOutput(1), Op::FocusOutput(2), + Op::AddNamedWorkspace { + ws_name: 1, + output_name: Some(1), + }, + Op::UnnameWorkspace { ws_name: 1 }, Op::AddWindow { id: 0, bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)), @@ -2874,6 +3177,12 @@ mod tests { bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)), min_max_size: Default::default(), }, + Op::AddWindowToNamedWorkspace { + id: 5, + ws_name: 1, + bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)), + min_max_size: Default::default(), + }, Op::CloseWindow(0), Op::CloseWindow(1), Op::CloseWindow(2), diff --git a/src/layout/monitor.rs b/src/layout/monitor.rs index 390abf0c..9dcc552e 100644 --- a/src/layout/monitor.rs +++ b/src/layout/monitor.rs @@ -103,6 +103,18 @@ impl Monitor { &self.workspaces[self.active_workspace_idx] } + pub fn find_named_workspace(&self, workspace_name: &str) -> Option<&Workspace> { + self.workspaces + .iter() + .find(|w| w.name.as_deref() == Some(workspace_name)) + } + + pub fn find_named_workspace_index(&self, workspace_name: &str) -> Option { + self.workspaces + .iter() + .position(|w| w.name.as_deref() == Some(workspace_name)) + } + pub fn active_workspace(&mut self) -> &mut Workspace { &mut self.workspaces[self.active_workspace_idx] } @@ -204,7 +216,7 @@ impl Monitor { continue; } - if !self.workspaces[idx].has_windows() { + if !self.workspaces[idx].has_windows() && self.workspaces[idx].name.is_none() { self.workspaces.remove(idx); if self.active_workspace_idx > idx { self.active_workspace_idx -= 1; @@ -213,6 +225,16 @@ impl Monitor { } } + pub fn unname_workspace(&mut self, workspace_name: &str) -> bool { + for ws in &mut self.workspaces { + if ws.name.as_deref() == Some(workspace_name) { + ws.unname(); + return true; + } + } + false + } + pub fn move_left(&mut self) { self.active_workspace().move_left(); } diff --git a/src/layout/workspace.rs b/src/layout/workspace.rs index 4a6ad91c..827228c6 100644 --- a/src/layout/workspace.rs +++ b/src/layout/workspace.rs @@ -3,7 +3,7 @@ use std::iter::{self, zip}; use std::rc::Rc; use std::time::Duration; -use niri_config::{CenterFocusedColumn, PresetWidth, Struts}; +use niri_config::{CenterFocusedColumn, PresetWidth, Struts, Workspace as WorkspaceConfig}; use niri_ipc::SizeChange; use smithay::backend::renderer::gles::GlesRenderer; use smithay::desktop::{layer_map_for_output, Window}; @@ -94,6 +94,9 @@ pub struct Workspace { /// Configurable properties of the layout. pub options: Rc, + /// Optional name of this workspace. + pub name: Option, + /// Unique ID of this workspace. id: WorkspaceId, } @@ -313,9 +316,23 @@ impl TileData { impl Workspace { pub fn new(output: Output, options: Rc) -> Self { + Self::new_with_config(output, None, options) + } + + pub fn new_with_config( + output: Output, + config: Option, + options: Rc, + ) -> Self { + let original_output = config + .as_ref() + .and_then(|c| c.open_on_output.clone()) + .map(OutputId) + .unwrap_or(OutputId::new(&output)); + let working_area = compute_working_area(&output, options.struts); Self { - original_output: OutputId::new(&output), + original_output, view_size: output_size(&output), working_area, output: Some(output), @@ -329,14 +346,24 @@ impl Workspace { view_offset_before_fullscreen: None, closing_windows: vec![], options, + name: config.map(|c| c.name.0), id: WorkspaceId::next(), } } - pub fn new_no_outputs(options: Rc) -> Self { + pub fn new_with_config_no_outputs( + config: Option, + options: Rc, + ) -> Self { + let original_output = OutputId( + config + .clone() + .and_then(|c| c.open_on_output) + .unwrap_or_default(), + ); Self { output: None, - original_output: OutputId(String::new()), + original_output, view_size: Size::from((1280, 720)), working_area: Rectangle::from_loc_and_size((0, 0), (1280, 720)), columns: vec![], @@ -349,14 +376,23 @@ impl Workspace { view_offset_before_fullscreen: None, closing_windows: vec![], options, + name: config.map(|c| c.name.0), id: WorkspaceId::next(), } } + pub fn new_no_outputs(options: Rc) -> Self { + Self::new_with_config_no_outputs(None, options) + } + pub fn id(&self) -> WorkspaceId { self.id } + pub fn unname(&mut self) { + self.name = None; + } + pub fn advance_animations(&mut self, current_time: Duration) { if let Some(ViewOffsetAdjustment::Animation(anim)) = &mut self.view_offset_adj { anim.set_current_time(current_time); @@ -435,6 +471,10 @@ impl Workspace { .map(Tile::window_mut) } + pub fn current_output(&self) -> Option<&Output> { + self.output.as_ref() + } + pub fn set_output(&mut self, output: Option) { if self.output == output { return; diff --git a/src/niri.rs b/src/niri.rs index a8d906c1..f054250c 100644 --- a/src/niri.rs +++ b/src/niri.rs @@ -11,7 +11,7 @@ use std::{env, mem, thread}; use _server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as KdeDecorationsMode; use anyhow::{ensure, Context}; use calloop::futures::Scheduler; -use niri_config::{Config, Key, Modifiers, PreviewRender, TrackLayout}; +use niri_config::{Config, Key, Modifiers, PreviewRender, TrackLayout, WorkspaceReference}; use smithay::backend::allocator::Fourcc; use smithay::backend::renderer::damage::OutputDamageTracker; use smithay::backend::renderer::element::memory::MemoryRenderBufferRenderElement; @@ -857,8 +857,24 @@ impl State { self.niri.config_error_notification.hide(); + // Find & orphan removed named workspaces. + let mut removed_workspaces: Vec = vec![]; + for ws in &self.niri.config.borrow().workspaces { + if !config.workspaces.iter().any(|w| w.name == ws.name) { + removed_workspaces.push(ws.name.0.clone()); + } + } + for name in removed_workspaces { + self.niri.layout.unname_workspace(&name); + } + self.niri.layout.update_config(&config); + // Create new named workspaces. + for ws_config in &config.workspaces { + self.niri.layout.ensure_named_workspace(ws_config); + } + let slowdown = if config.animations.off { 0. } else { @@ -2097,6 +2113,38 @@ impl Niri { .cloned() } + pub fn output_by_name(&self, name: &str) -> Option { + self.global_space + .outputs() + .find(|output| output.name().eq_ignore_ascii_case(name)) + .cloned() + } + + pub fn find_output_and_workspace_index( + &self, + workspace_reference: WorkspaceReference, + ) -> Option<(Option, usize)> { + let workspace_name = match workspace_reference { + WorkspaceReference::Index(index) => { + return Some((None, index.saturating_sub(1) as usize)); + } + WorkspaceReference::Name(name) => name, + }; + + let (target_workspace_index, target_workspace) = + self.layout.find_workspace_by_name(&workspace_name)?; + + // FIXME: when we do fixes for no connected outputs, this will need fixing too. + let active_workspace = self.layout.active_workspace()?; + + if target_workspace.current_output() == active_workspace.current_output() { + return Some((None, target_workspace_index)); + } + let target_output = target_workspace.current_output()?; + + Some((Some(target_output.clone()), target_workspace_index)) + } + pub fn output_down(&self) -> Option { let active = self.layout.active_output()?; let active_geo = self.global_space.output_geometry(active).unwrap(); diff --git a/src/window/mod.rs b/src/window/mod.rs index 4ccbb111..92b4f793 100644 --- a/src/window/mod.rs +++ b/src/window/mod.rs @@ -33,6 +33,9 @@ pub struct ResolvedWindowRules { /// Output to open this window on. pub open_on_output: Option, + /// Workspace to open this window on. + pub open_on_workspace: Option, + /// Whether the window should open full-width. pub open_maximized: Option, @@ -99,6 +102,7 @@ impl ResolvedWindowRules { Self { default_width: None, open_on_output: None, + open_on_workspace: None, open_maximized: None, open_fullscreen: None, min_width: None, @@ -151,6 +155,7 @@ impl ResolvedWindowRules { } let mut open_on_output = None; + let mut open_on_workspace = None; for rule in rules { let matches = |m| window_matches(window, &role, m); @@ -175,6 +180,10 @@ impl ResolvedWindowRules { open_on_output = Some(x); } + if let Some(x) = rule.open_on_workspace.as_deref() { + open_on_workspace = Some(x); + } + if let Some(x) = rule.open_maximized { resolved.open_maximized = Some(x); } @@ -217,6 +226,7 @@ impl ResolvedWindowRules { } resolved.open_on_output = open_on_output.map(|x| x.to_owned()); + resolved.open_on_workspace = open_on_workspace.map(|x| x.to_owned()); }); resolved diff --git a/src/window/unmapped.rs b/src/window/unmapped.rs index 9cde4ca7..a74c4e24 100644 --- a/src/window/unmapped.rs +++ b/src/window/unmapped.rs @@ -11,6 +11,7 @@ pub struct Unmapped { pub state: InitialConfigureState, } +#[allow(clippy::large_enum_variant)] #[derive(Debug)] pub enum InitialConfigureState { /// The window has not been initially configured yet. @@ -42,6 +43,9 @@ pub enum InitialConfigureState { /// - This is a dialog with a parent, and there was no explicit output set, so this dialog /// should fetch the parent's current output again upon mapping. output: Option, + + /// Workspace to open this window on. + workspace_name: Option, }, }