forge
Explore
Log in

Don't you dare go Hollow

Implement named workspaces

Browse files at this commit

eb9bbe3352820754a4ee3c19f15cff690d1c193dGergely NagyParent: 229ca90
This is an implementation of named, pre-declared workspaces. With this
implementation, workspaces can be declared in the configuration file by
name:

```
workspace "name" {
  open-on-output "winit"
}
```

The `open-on-output` property is optional, and can be skipped, in which
case the workspace will open on the primary output.

All actions that were able to target a workspace by index can now target
them by either an index, or a name. In case of the command line, where
we do not have types available, this means that workspace names that
also pass as `u8` cannot be switched to by name, only by index.

Unlike dynamic workspaces, named workspaces do not close when they are
empty, they remain static. Like dynamic workspaces, named workspaces are
bound to a particular output. Switching to a named workspace, or moving
a window or column to one will also switch to, or move the thing in
question to the output of the workspace.

When reloading the configuration, newly added named workspaces will be
created, and removed ones will lose their name. If any such orphaned
workspace was empty, they will be removed. If they weren't, they'll
remain as a dynamic workspace, without a name. Re-declaring a workspace
with the same name later will create a new one.

Additionally, this also implements a `open-on-workspace "<name>"` window
rule. Matching windows will open on the given workspace (or the current
one, if the named workspace does not exist).

Signed-off-by: Gergely Nagy <niri@gergo.csillger.hu>
niri-config/src/lib.rsmodified+162 -8
@@ -11,7 +11,7 @@ use bitflags::bitflags;
1111 use knuffel::errors::DecodeError;
1212 use knuffel::Decode as _;
1313 use miette::{miette, Context, IntoDiagnostic, NarratableReportHandler};
14-use niri_ipc::{ConfiguredMode, LayoutSwitchTarget, SizeChange, Transform};
14+use niri_ipc::{ConfiguredMode, LayoutSwitchTarget, SizeChange, Transform, WorkspaceReferenceArg};
1515 use regex::Regex;
1616 use smithay::input::keyboard::keysyms::KEY_NoSymbol;
1717 use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE};
@@ -52,6 +52,8 @@ pub struct Config {
5252 pub binds: Binds,
5353 #[knuffel(child, default)]
5454 pub debug: DebugConfig,
55+ #[knuffel(children(name = "workspace"))]
56+ pub workspaces: Vec<Workspace>,
5557 }
5658
5759 // FIXME: Add other devices.
@@ -693,6 +695,17 @@ pub struct EnvironmentVariable {
693695 pub value: Option<String>,
694696 }
695697
698+#[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)]
699+pub struct Workspace {
700+ #[knuffel(argument)]
701+ pub name: WorkspaceName,
702+ #[knuffel(child, unwrap(argument))]
703+ pub open_on_output: Option<String>,
704+}
705+
706+#[derive(Debug, Clone, PartialEq, Eq)]
707+pub struct WorkspaceName(pub String);
708+
696709 #[derive(knuffel::Decode, Debug, Default, Clone, PartialEq)]
697710 pub struct WindowRule {
698711 #[knuffel(children(name = "match"))]
@@ -706,6 +719,8 @@ pub struct WindowRule {
706719 #[knuffel(child, unwrap(argument))]
707720 pub open_on_output: Option<String>,
708721 #[knuffel(child, unwrap(argument))]
722+ pub open_on_workspace: Option<String>,
723+ #[knuffel(child, unwrap(argument))]
709724 pub open_maximized: Option<bool>,
710725 #[knuffel(child, unwrap(argument))]
711726 pub open_fullscreen: Option<bool>,
@@ -890,14 +905,14 @@ pub enum Action {
890905 CenterColumn,
891906 FocusWorkspaceDown,
892907 FocusWorkspaceUp,
893- FocusWorkspace(#[knuffel(argument)] u8),
908+ FocusWorkspace(#[knuffel(argument)] WorkspaceReference),
894909 FocusWorkspacePrevious,
895910 MoveWindowToWorkspaceDown,
896911 MoveWindowToWorkspaceUp,
897- MoveWindowToWorkspace(#[knuffel(argument)] u8),
912+ MoveWindowToWorkspace(#[knuffel(argument)] WorkspaceReference),
898913 MoveColumnToWorkspaceDown,
899914 MoveColumnToWorkspaceUp,
900- MoveColumnToWorkspace(#[knuffel(argument)] u8),
915+ MoveColumnToWorkspace(#[knuffel(argument)] WorkspaceReference),
901916 MoveWorkspaceDown,
902917 MoveWorkspaceUp,
903918 FocusMonitorLeft,
@@ -962,14 +977,20 @@ impl From<niri_ipc::Action> for Action {
962977 niri_ipc::Action::CenterColumn => Self::CenterColumn,
963978 niri_ipc::Action::FocusWorkspaceDown => Self::FocusWorkspaceDown,
964979 niri_ipc::Action::FocusWorkspaceUp => Self::FocusWorkspaceUp,
965- niri_ipc::Action::FocusWorkspace { index } => Self::FocusWorkspace(index),
980+ niri_ipc::Action::FocusWorkspace { reference } => {
981+ Self::FocusWorkspace(WorkspaceReference::from(reference))
982+ }
966983 niri_ipc::Action::FocusWorkspacePrevious => Self::FocusWorkspacePrevious,
967984 niri_ipc::Action::MoveWindowToWorkspaceDown => Self::MoveWindowToWorkspaceDown,
968985 niri_ipc::Action::MoveWindowToWorkspaceUp => Self::MoveWindowToWorkspaceUp,
969- niri_ipc::Action::MoveWindowToWorkspace { index } => Self::MoveWindowToWorkspace(index),
986+ niri_ipc::Action::MoveWindowToWorkspace { reference } => {
987+ Self::MoveWindowToWorkspace(WorkspaceReference::from(reference))
988+ }
970989 niri_ipc::Action::MoveColumnToWorkspaceDown => Self::MoveColumnToWorkspaceDown,
971990 niri_ipc::Action::MoveColumnToWorkspaceUp => Self::MoveColumnToWorkspaceUp,
972- niri_ipc::Action::MoveColumnToWorkspace { index } => Self::MoveColumnToWorkspace(index),
991+ niri_ipc::Action::MoveColumnToWorkspace { reference } => {
992+ Self::MoveColumnToWorkspace(WorkspaceReference::from(reference))
993+ }
973994 niri_ipc::Action::MoveWorkspaceDown => Self::MoveWorkspaceDown,
974995 niri_ipc::Action::MoveWorkspaceUp => Self::MoveWorkspaceUp,
975996 niri_ipc::Action::FocusMonitorLeft => Self::FocusMonitorLeft,
@@ -1002,6 +1023,59 @@ impl From<niri_ipc::Action> for Action {
10021023 }
10031024 }
10041025
1026+#[derive(Debug, PartialEq, Eq, Clone)]
1027+pub enum WorkspaceReference {
1028+ Index(u8),
1029+ Name(String),
1030+}
1031+
1032+impl From<WorkspaceReferenceArg> for WorkspaceReference {
1033+ fn from(reference: WorkspaceReferenceArg) -> WorkspaceReference {
1034+ match reference {
1035+ WorkspaceReferenceArg::Index(i) => Self::Index(i),
1036+ WorkspaceReferenceArg::Name(n) => Self::Name(n),
1037+ }
1038+ }
1039+}
1040+
1041+impl<S: knuffel::traits::ErrorSpan> knuffel::DecodeScalar<S> for WorkspaceReference {
1042+ fn type_check(
1043+ type_name: &Option<knuffel::span::Spanned<knuffel::ast::TypeName, S>>,
1044+ ctx: &mut knuffel::decode::Context<S>,
1045+ ) {
1046+ if let Some(type_name) = &type_name {
1047+ ctx.emit_error(DecodeError::unexpected(
1048+ type_name,
1049+ "type name",
1050+ "no type name expected for this node",
1051+ ));
1052+ }
1053+ }
1054+
1055+ fn raw_decode(
1056+ val: &knuffel::span::Spanned<knuffel::ast::Literal, S>,
1057+ ctx: &mut knuffel::decode::Context<S>,
1058+ ) -> Result<WorkspaceReference, DecodeError<S>> {
1059+ match &**val {
1060+ knuffel::ast::Literal::String(ref s) => Ok(WorkspaceReference::Name(s.clone().into())),
1061+ knuffel::ast::Literal::Int(ref value) => match value.try_into() {
1062+ Ok(v) => Ok(WorkspaceReference::Index(v)),
1063+ Err(e) => {
1064+ ctx.emit_error(DecodeError::conversion(val, e));
1065+ Ok(WorkspaceReference::Index(0))
1066+ }
1067+ },
1068+ _ => {
1069+ ctx.emit_error(DecodeError::unsupported(
1070+ val,
1071+ "Unsupported value, only numbers and strings are recognized",
1072+ ));
1073+ Ok(WorkspaceReference::Index(0))
1074+ }
1075+ }
1076+ }
1077+}
1078+
10051079 #[derive(knuffel::Decode, Debug, Default, PartialEq)]
10061080 pub struct DebugConfig {
10071081 #[knuffel(child, unwrap(argument))]
@@ -1409,6 +1483,54 @@ where
14091483 }
14101484 }
14111485
1486+impl<S: knuffel::traits::ErrorSpan> knuffel::DecodeScalar<S> for WorkspaceName {
1487+ fn type_check(
1488+ type_name: &Option<knuffel::span::Spanned<knuffel::ast::TypeName, S>>,
1489+ ctx: &mut knuffel::decode::Context<S>,
1490+ ) {
1491+ if let Some(type_name) = &type_name {
1492+ ctx.emit_error(DecodeError::unexpected(
1493+ type_name,
1494+ "type name",
1495+ "no type name expected for this node",
1496+ ));
1497+ }
1498+ }
1499+
1500+ fn raw_decode(
1501+ val: &knuffel::span::Spanned<knuffel::ast::Literal, S>,
1502+ ctx: &mut knuffel::decode::Context<S>,
1503+ ) -> Result<WorkspaceName, DecodeError<S>> {
1504+ #[derive(Debug)]
1505+ struct WorkspaceNameSet(HashSet<String>);
1506+ match &**val {
1507+ knuffel::ast::Literal::String(ref s) => {
1508+ let mut name_set: HashSet<String> = match ctx.get::<WorkspaceNameSet>() {
1509+ Some(h) => h.0.clone(),
1510+ None => HashSet::new(),
1511+ };
1512+ if !name_set.insert(s.clone().to_string()) {
1513+ ctx.emit_error(DecodeError::unexpected(
1514+ val,
1515+ "named workspace",
1516+ format!("duplicate named workspace: {}", s),
1517+ ));
1518+ return Ok(Self(String::new()));
1519+ }
1520+ ctx.set(WorkspaceNameSet(name_set));
1521+ Ok(Self(s.clone().into()))
1522+ }
1523+ _ => {
1524+ ctx.emit_error(DecodeError::unsupported(
1525+ val,
1526+ "workspace names must be strings",
1527+ ));
1528+ Ok(Self(String::new()))
1529+ }
1530+ }
1531+ }
1532+}
1533+
14121534 impl<S> knuffel::Decode<S> for WindowOpenAnim
14131535 where
14141536 S: knuffel::traits::ErrorSpan,
@@ -2278,6 +2400,7 @@ mod tests {
22782400 Mod+Ctrl+Shift+L { move-window-to-monitor-right; }
22792401 Mod+Comma { consume-window-into-column; }
22802402 Mod+1 { focus-workspace 1; }
2403+ Mod+Shift+1 { focus-workspace "workspace-1"; }
22812404 Mod+Shift+E { quit skip-confirmation=true; }
22822405 Mod+WheelScrollDown cooldown-ms=150 { focus-workspace-down; }
22832406 }
@@ -2285,6 +2408,12 @@ mod tests {
22852408 debug {
22862409 render-drm-device "/dev/dri/renderD129"
22872410 }
2411+
2412+ workspace "workspace-1" {
2413+ open-on-output "eDP-1"
2414+ }
2415+ workspace "workspace-2"
2416+ workspace "workspace-3"
22882417 "##,
22892418 Config {
22902419 input: Input {
@@ -2489,6 +2618,20 @@ mod tests {
24892618 },
24902619 ..Default::default()
24912620 }],
2621+ workspaces: vec![
2622+ Workspace {
2623+ name: WorkspaceName("workspace-1".to_string()),
2624+ open_on_output: Some("eDP-1".to_string()),
2625+ },
2626+ Workspace {
2627+ name: WorkspaceName("workspace-2".to_string()),
2628+ open_on_output: None,
2629+ },
2630+ Workspace {
2631+ name: WorkspaceName("workspace-3".to_string()),
2632+ open_on_output: None,
2633+ },
2634+ ],
24922635 binds: Binds(vec![
24932636 Bind {
24942637 key: Key {
@@ -2540,7 +2683,18 @@ mod tests {
25402683 trigger: Trigger::Keysym(Keysym::_1),
25412684 modifiers: Modifiers::COMPOSITOR,
25422685 },
2543- action: Action::FocusWorkspace(1),
2686+ action: Action::FocusWorkspace(WorkspaceReference::Index(1)),
2687+ cooldown: None,
2688+ allow_when_locked: false,
2689+ },
2690+ Bind {
2691+ key: Key {
2692+ trigger: Trigger::Keysym(Keysym::_1),
2693+ modifiers: Modifiers::COMPOSITOR | Modifiers::SHIFT,
2694+ },
2695+ action: Action::FocusWorkspace(WorkspaceReference::Name(
2696+ "workspace-1".to_string(),
2697+ )),
25442698 cooldown: None,
25452699 allow_when_locked: false,
25462700 },
niri-ipc/src/lib.rsmodified+36 -9
@@ -146,11 +146,11 @@ pub enum Action {
146146 FocusWorkspaceDown,
147147 /// Focus the workspace above.
148148 FocusWorkspaceUp,
149- /// Focus a workspace by index.
149+ /// Focus a workspace by reference (index or name).
150150 FocusWorkspace {
151- /// Index of the workspace to focus.
151+ /// Reference (index or name) of the workspace to focus.
152152 #[cfg_attr(feature = "clap", arg())]
153- index: u8,
153+ reference: WorkspaceReferenceArg,
154154 },
155155 /// Focus the previous workspace.
156156 FocusWorkspacePrevious,
@@ -158,21 +158,21 @@ pub enum Action {
158158 MoveWindowToWorkspaceDown,
159159 /// Move the focused window to the workspace above.
160160 MoveWindowToWorkspaceUp,
161- /// Move the focused window to a workspace by index.
161+ /// Move the focused window to a workspace by reference (index or name).
162162 MoveWindowToWorkspace {
163- /// Index of the target workspace.
163+ /// Reference (index or name) of the workspace to move the window to.
164164 #[cfg_attr(feature = "clap", arg())]
165- index: u8,
165+ reference: WorkspaceReferenceArg,
166166 },
167167 /// Move the focused column to the workspace below.
168168 MoveColumnToWorkspaceDown,
169169 /// Move the focused column to the workspace above.
170170 MoveColumnToWorkspaceUp,
171- /// Move the focused column to a workspace by index.
171+ /// Move the focused column to a workspace by reference (index or name).
172172 MoveColumnToWorkspace {
173- /// Index of the target workspace.
173+ /// Reference (index or name) of the workspace to move the column to.
174174 #[cfg_attr(feature = "clap", arg())]
175- index: u8,
175+ reference: WorkspaceReferenceArg,
176176 },
177177 /// Move the focused workspace down.
178178 MoveWorkspaceDown,
@@ -257,6 +257,15 @@ pub enum SizeChange {
257257 AdjustProportion(f64),
258258 }
259259
260+/// Workspace reference (index or name) to operate on.
261+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
262+pub enum WorkspaceReferenceArg {
263+ /// Index of the workspace.
264+ Index(u8),
265+ /// Name of the workspace.
266+ Name(String),
267+}
268+
260269 /// Layout to switch to.
261270 #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
262271 pub enum LayoutSwitchTarget {
@@ -475,6 +484,24 @@ pub enum OutputConfigChanged {
475484 OutputWasMissing,
476485 }
477486
487+impl FromStr for WorkspaceReferenceArg {
488+ type Err = &'static str;
489+
490+ fn from_str(s: &str) -> Result<Self, Self::Err> {
491+ let reference = if let Ok(index) = s.parse::<i32>() {
492+ if let Ok(idx) = u8::try_from(index) {
493+ Self::Index(idx)
494+ } else {
495+ return Err("workspace indexes must be between 0 and 255");
496+ }
497+ } else {
498+ Self::Name(s.to_string())
499+ };
500+
501+ Ok(reference)
502+ }
503+}
504+
478505 impl FromStr for SizeChange {
479506 type Err = &'static str;
480507
src/handlers/compositor.rsmodified+15 -3
@@ -119,22 +119,27 @@ impl CompositorHandler for State {
119119
120120 let toplevel = window.toplevel().expect("no X11 support");
121121
122- let (rules, width, is_full_width, output) =
122+ let (rules, width, is_full_width, output, workspace_name) =
123123 if let InitialConfigureState::Configured {
124124 rules,
125125 width,
126126 is_full_width,
127127 output,
128+ workspace_name,
128129 } = state
129130 {
130131 // Check that the output is still connected.
131132 let output =
132133 output.filter(|o| self.niri.layout.monitor_for_output(o).is_some());
133134
134- (rules, width, is_full_width, output)
135+ // Chech that the workspace still exists.
136+ let workspace_name = workspace_name
137+ .filter(|n| self.niri.layout.find_workspace_by_name(n).is_some());
138+
139+ (rules, width, is_full_width, output, workspace_name)
135140 } else {
136141 error!("window map must happen after initial configure");
137- (ResolvedWindowRules::empty(), None, false, None)
142+ (ResolvedWindowRules::empty(), None, false, None, None)
138143 };
139144
140145 let parent = toplevel
@@ -160,6 +165,13 @@ impl CompositorHandler for State {
160165 self.niri
161166 .layout
162167 .add_window_right_of(&p, mapped, width, is_full_width)
168+ } else if let Some(workspace_name) = &workspace_name {
169+ self.niri.layout.add_window_to_named_workspace(
170+ workspace_name,
171+ mapped,
172+ width,
173+ is_full_width,
174+ )
163175 } else if let Some(output) = &output {
164176 self.niri
165177 .layout
src/handlers/xdg_shell.rsmodified+58 -30
@@ -369,38 +369,52 @@ impl XdgShellHandler for State {
369369 width,
370370 is_full_width,
371371 output,
372+ workspace_name,
372373 } => {
373374 // Figure out the monitor following a similar logic to initial configure.
374375 // FIXME: deduplicate.
375- let mon = output
376- .as_ref()
377- .and_then(|o| self.niri.layout.monitor_for_output(o))
378- .map(|mon| (mon, false))
379- // If not, check if we have a parent with a monitor.
380- .or_else(|| {
381- toplevel
382- .parent()
383- .and_then(|parent| self.niri.layout.find_window_and_output(&parent))
384- .map(|(_win, output)| output)
385- .and_then(|o| self.niri.layout.monitor_for_output(o))
386- .map(|mon| (mon, true))
387- })
388- // If not, fall back to the active monitor.
389- .or_else(|| {
390- self.niri
391- .layout
392- .active_monitor_ref()
393- .map(|mon| (mon, false))
394- });
376+ let mon = workspace_name
377+ .as_deref()
378+ .and_then(|name| self.niri.layout.monitor_for_workspace(name))
379+ .map(|mon| (mon, false));
380+
381+ let mon = mon.or_else(|| {
382+ output
383+ .as_ref()
384+ .and_then(|o| self.niri.layout.monitor_for_output(o))
385+ .map(|mon| (mon, false))
386+ // If not, check if we have a parent with a monitor.
387+ .or_else(|| {
388+ toplevel
389+ .parent()
390+ .and_then(|parent| {
391+ self.niri.layout.find_window_and_output(&parent)
392+ })
393+ .map(|(_win, output)| output)
394+ .and_then(|o| self.niri.layout.monitor_for_output(o))
395+ .map(|mon| (mon, true))
396+ })
397+ // If not, fall back to the active monitor.
398+ .or_else(|| {
399+ self.niri
400+ .layout
401+ .active_monitor_ref()
402+ .map(|mon| (mon, false))
403+ })
404+ });
395405
396406 *output = mon
397407 .filter(|(_, parent)| !parent)
398408 .map(|(mon, _)| mon.output.clone());
399409 let mon = mon.map(|(mon, _)| mon);
400410
401- let ws = mon
402- .map(|mon| mon.active_workspace_ref())
403- .or_else(|| self.niri.layout.active_workspace());
411+ let ws = workspace_name
412+ .as_deref()
413+ .and_then(|name| mon.map(|mon| mon.find_named_workspace(name)))
414+ .unwrap_or_else(|| {
415+ mon.map(|mon| mon.active_workspace_ref())
416+ .or_else(|| self.niri.layout.active_workspace())
417+ });
404418
405419 if let Some(ws) = ws {
406420 toplevel.with_pending_state(|state| {
@@ -577,12 +591,20 @@ impl State {
577591 return;
578592 };
579593
580- // Pick the target monitor. First, check if we had an output set in the window rules.
594+ // Pick the target monitor. First, check if we had a workspace set in the window rules.
581595 let mon = rules
582- .open_on_output
596+ .open_on_workspace
583597 .as_deref()
584- .and_then(|name| self.niri.output_by_name.get(name))
585- .and_then(|o| self.niri.layout.monitor_for_output(o));
598+ .and_then(|name| self.niri.layout.monitor_for_workspace(name));
599+
600+ // If not, check if we had an output set in the window rules.
601+ let mon = mon.or_else(|| {
602+ rules
603+ .open_on_output
604+ .as_deref()
605+ .and_then(|name| self.niri.output_by_name.get(name))
606+ .and_then(|o| self.niri.layout.monitor_for_output(o))
607+ });
586608
587609 // If not, check if the window requested one for fullscreen.
588610 let mon = mon.or_else(|| {
@@ -622,9 +644,14 @@ impl State {
622644 let is_full_width = rules.open_maximized.unwrap_or(false);
623645
624646 // Tell the surface the preferred size and bounds for its likely output.
625- let ws = mon
626- .map(|mon| mon.active_workspace_ref())
627- .or_else(|| self.niri.layout.active_workspace());
647+ let ws = rules
648+ .open_on_workspace
649+ .as_deref()
650+ .and_then(|name| mon.map(|mon| mon.find_named_workspace(name)))
651+ .unwrap_or_else(|| {
652+ mon.map(|mon| mon.active_workspace_ref())
653+ .or_else(|| self.niri.layout.active_workspace())
654+ });
628655
629656 if let Some(ws) = ws {
630657 // Set a fullscreen state based on window request and window rule.
@@ -663,6 +690,7 @@ impl State {
663690 width,
664691 is_full_width,
665692 output,
693+ workspace_name: ws.and_then(|w| w.name.clone()),
666694 };
667695
668696 toplevel.send_configure();
src/input/mod.rsmodified+54 -23
@@ -587,12 +587,22 @@ impl State {
587587 // FIXME: granular
588588 self.niri.queue_redraw_all();
589589 }
590- Action::MoveWindowToWorkspace(idx) => {
591- let idx = idx.saturating_sub(1) as usize;
592- self.niri.layout.move_to_workspace(idx);
593- self.maybe_warp_cursor_to_focus();
594- // FIXME: granular
595- self.niri.queue_redraw_all();
590+ Action::MoveWindowToWorkspace(reference) => {
591+ if let Some((output, index)) = self.niri.find_output_and_workspace_index(reference)
592+ {
593+ if let Some(output) = output {
594+ self.niri.layout.move_to_workspace_on_output(&output, index);
595+ if !self.maybe_warp_cursor_to_focus_centered() {
596+ self.move_cursor_to_output(&output);
597+ }
598+ } else {
599+ self.niri.layout.move_to_workspace(index);
600+ self.maybe_warp_cursor_to_focus();
601+ }
602+
603+ // FIXME: granular
604+ self.niri.queue_redraw_all();
605+ }
596606 }
597607 Action::MoveColumnToWorkspaceDown => {
598608 self.niri.layout.move_column_to_workspace_down();
@@ -606,12 +616,24 @@ impl State {
606616 // FIXME: granular
607617 self.niri.queue_redraw_all();
608618 }
609- Action::MoveColumnToWorkspace(idx) => {
610- let idx = idx.saturating_sub(1) as usize;
611- self.niri.layout.move_column_to_workspace(idx);
612- self.maybe_warp_cursor_to_focus();
613- // FIXME: granular
614- self.niri.queue_redraw_all();
619+ Action::MoveColumnToWorkspace(reference) => {
620+ if let Some((output, index)) = self.niri.find_output_and_workspace_index(reference)
621+ {
622+ if let Some(output) = output {
623+ self.niri
624+ .layout
625+ .move_column_to_workspace_on_output(&output, index);
626+ if !self.maybe_warp_cursor_to_focus_centered() {
627+ self.move_cursor_to_output(&output);
628+ }
629+ } else {
630+ self.niri.layout.move_column_to_workspace(index);
631+ self.maybe_warp_cursor_to_focus();
632+ }
633+
634+ // FIXME: granular
635+ self.niri.queue_redraw_all();
636+ }
615637 }
616638 Action::FocusWorkspaceDown => {
617639 self.niri.layout.switch_workspace_down();
@@ -625,19 +647,28 @@ impl State {
625647 // FIXME: granular
626648 self.niri.queue_redraw_all();
627649 }
628- Action::FocusWorkspace(idx) => {
629- let idx = idx.saturating_sub(1) as usize;
650+ Action::FocusWorkspace(reference) => {
651+ if let Some((output, index)) = self.niri.find_output_and_workspace_index(reference)
652+ {
653+ if let Some(output) = output {
654+ self.niri.layout.focus_output(&output);
655+ self.niri.layout.switch_workspace(index);
656+ if !self.maybe_warp_cursor_to_focus_centered() {
657+ self.move_cursor_to_output(&output);
658+ }
659+ } else {
660+ let config = &self.niri.config;
661+ if config.borrow().input.workspace_auto_back_and_forth {
662+ self.niri.layout.switch_workspace_auto_back_and_forth(index);
663+ } else {
664+ self.niri.layout.switch_workspace(index);
665+ }
666+ self.maybe_warp_cursor_to_focus();
667+ }
630668
631- let config = &self.niri.config;
632- if config.borrow().input.workspace_auto_back_and_forth {
633- self.niri.layout.switch_workspace_auto_back_and_forth(idx);
634- } else {
635- self.niri.layout.switch_workspace(idx);
669+ // FIXME: granular
670+ self.niri.queue_redraw_all();
636671 }
637-
638- self.maybe_warp_cursor_to_focus();
639- // FIXME: granular
640- self.niri.queue_redraw_all();
641672 }
642673 Action::FocusWorkspacePrevious => {
643674 self.niri.layout.switch_workspace_previous();
src/layout/mod.rsmodified+329 -20
@@ -34,7 +34,7 @@ use std::mem;
3434 use std::rc::Rc;
3535 use std::time::Duration;
3636
37-use niri_config::{CenterFocusedColumn, Config, Struts};
37+use niri_config::{CenterFocusedColumn, Config, Struts, Workspace as WorkspaceConfig};
3838 use niri_ipc::SizeChange;
3939 use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
4040 use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
@@ -279,7 +279,7 @@ impl Options {
279279
280280 impl<W: LayoutElement> Layout<W> {
281281 pub fn new(config: &Config) -> Self {
282- Self::with_options(Options::from_config(config))
282+ Self::with_options_and_workspaces(config, Options::from_config(config))
283283 }
284284
285285 pub fn with_options(options: Options) -> Self {
@@ -289,6 +289,21 @@ impl<W: LayoutElement> Layout<W> {
289289 }
290290 }
291291
292+ fn with_options_and_workspaces(config: &Config, options: Options) -> Self {
293+ let opts = Rc::new(options);
294+
295+ let workspaces = config
296+ .workspaces
297+ .iter()
298+ .map(|ws| Workspace::new_with_config_no_outputs(Some(ws.clone()), opts.clone()))
299+ .collect();
300+
301+ Self {
302+ monitor_set: MonitorSet::NoOutputs { workspaces },
303+ options: opts,
304+ }
305+ }
306+
292307 pub fn add_output(&mut self, output: Output) {
293308 let id = OutputId::new(&output);
294309
@@ -318,7 +333,7 @@ impl<W: LayoutElement> Layout<W> {
318333 // The user could've closed a window while remaining on this workspace, on
319334 // another monitor. However, we will add an empty workspace in the end
320335 // instead.
321- if ws.has_windows() {
336+ if ws.has_windows() || ws.name.is_some() {
322337 workspaces.push(ws);
323338 }
324339
@@ -463,6 +478,67 @@ impl<W: LayoutElement> Layout<W> {
463478 }
464479 }
465480
481+ /// Adds a new window to the layout on a specific workspace.
482+ pub fn add_window_to_named_workspace(
483+ &mut self,
484+ workspace_name: &str,
485+ window: W,
486+ width: Option<ColumnWidth>,
487+ is_full_width: bool,
488+ ) -> Option<&Output> {
489+ let mut width = width.unwrap_or_else(|| ColumnWidth::Fixed(window.size().w));
490+ if let ColumnWidth::Fixed(w) = &mut width {
491+ let rules = window.rules();
492+ let border_config = rules.border.resolve_against(self.options.border);
493+ if !border_config.off {
494+ *w += border_config.width as i32 * 2;
495+ }
496+ }
497+
498+ match &mut self.monitor_set {
499+ MonitorSet::Normal {
500+ monitors,
501+ active_monitor_idx,
502+ ..
503+ } => {
504+ let (mon_idx, mon, ws_idx) = monitors
505+ .iter_mut()
506+ .enumerate()
507+ .find_map(|(mon_idx, mon)| {
508+ mon.find_named_workspace_index(workspace_name)
509+ .map(move |ws_idx| (mon_idx, mon, ws_idx))
510+ })
511+ .unwrap();
512+
513+ // Don't steal focus from an active fullscreen window.
514+ let mut activate = true;
515+ let ws = &mon.workspaces[ws_idx];
516+ if mon_idx == *active_monitor_idx
517+ && !ws.columns.is_empty()
518+ && ws.columns[ws.active_column_idx].is_fullscreen
519+ {
520+ activate = false;
521+ }
522+
523+ // Don't activate if on a different workspace.
524+ if mon.active_workspace_idx != ws_idx {
525+ activate = false;
526+ }
527+
528+ mon.add_window(ws_idx, window, activate, width, is_full_width);
529+ Some(&mon.output)
530+ }
531+ MonitorSet::NoOutputs { workspaces } => {
532+ let ws = workspaces
533+ .iter_mut()
534+ .find(|ws| ws.name.as_deref() == Some(workspace_name))
535+ .unwrap();
536+ ws.add_window(window, true, width, is_full_width);
537+ None
538+ }
539+ }
540+ }
541+
466542 pub fn add_column_by_idx(
467543 &mut self,
468544 monitor_idx: usize,
@@ -649,6 +725,7 @@ impl<W: LayoutElement> Layout<W> {
649725 && idx != mon.active_workspace_idx
650726 && idx != mon.workspaces.len() - 1
651727 && mon.workspace_switch.is_none()
728+ && mon.workspaces[idx].name.is_none()
652729 {
653730 mon.workspaces.remove(idx);
654731
@@ -668,7 +745,7 @@ impl<W: LayoutElement> Layout<W> {
668745 rv = Some(ws.remove_window(window));
669746
670747 // Clean up empty workspaces.
671- if !ws.has_windows() {
748+ if !ws.has_windows() && workspaces[idx].name.is_none() {
672749 workspaces.remove(idx);
673750 }
674751
@@ -718,6 +795,63 @@ impl<W: LayoutElement> Layout<W> {
718795 None
719796 }
720797
798+ pub fn find_workspace_by_name(&self, workspace_name: &str) -> Option<(usize, &Workspace<W>)> {
799+ match &self.monitor_set {
800+ MonitorSet::Normal { ref monitors, .. } => {
801+ for mon in monitors {
802+ if let Some((index, workspace)) = mon
803+ .workspaces
804+ .iter()
805+ .enumerate()
806+ .find(|(_, w)| w.name.as_deref() == Some(workspace_name))
807+ {
808+ return Some((index, workspace));
809+ }
810+ }
811+ }
812+ MonitorSet::NoOutputs { workspaces } => {
813+ if let Some((index, workspace)) = workspaces
814+ .iter()
815+ .enumerate()
816+ .find(|(_, w)| w.name.as_deref() == Some(workspace_name))
817+ {
818+ return Some((index, workspace));
819+ }
820+ }
821+ }
822+
823+ None
824+ }
825+
826+ pub fn unname_workspace(&mut self, workspace_name: &str) {
827+ match &mut self.monitor_set {
828+ MonitorSet::Normal { monitors, .. } => {
829+ for mon in monitors {
830+ if mon.unname_workspace(workspace_name) {
831+ if mon.workspace_switch.is_none() {
832+ mon.clean_up_workspaces();
833+ }
834+ return;
835+ }
836+ }
837+ }
838+ MonitorSet::NoOutputs { workspaces } => {
839+ for (idx, ws) in workspaces.iter_mut().enumerate() {
840+ if ws.name.as_deref() == Some(workspace_name) {
841+ ws.unname();
842+
843+ // Clean up empty workspaces.
844+ if !ws.has_windows() {
845+ workspaces.remove(idx);
846+ }
847+
848+ return;
849+ }
850+ }
851+ }
852+ }
853+ }
854+
721855 pub fn find_window_and_output_mut(
722856 &mut self,
723857 wl_surface: &WlSurface,
@@ -970,6 +1104,19 @@ impl<W: LayoutElement> Layout<W> {
9701104 monitors.iter().find(|monitor| &monitor.output == output)
9711105 }
9721106
1107+ pub fn monitor_for_workspace(&self, workspace_name: &str) -> Option<&Monitor<W>> {
1108+ let MonitorSet::Normal { monitors, .. } = &self.monitor_set else {
1109+ return None;
1110+ };
1111+
1112+ monitors.iter().find(|monitor| {
1113+ monitor
1114+ .workspaces
1115+ .iter()
1116+ .any(|ws| ws.name.as_deref() == Some(workspace_name))
1117+ })
1118+ }
1119+
9731120 pub fn outputs(&self) -> impl Iterator<Item = &Output> + '_ {
9741121 let monitors = if let MonitorSet::Normal { monitors, .. } = &self.monitor_set {
9751122 &monitors[..]
@@ -1127,6 +1274,12 @@ impl<W: LayoutElement> Layout<W> {
11271274 monitor.move_to_workspace(idx);
11281275 }
11291276
1277+ pub fn move_to_workspace_on_output(&mut self, output: &Output, idx: usize) {
1278+ self.move_to_output(output);
1279+ self.focus_output(output);
1280+ self.move_to_workspace(idx);
1281+ }
1282+
11301283 pub fn move_column_to_workspace_up(&mut self) {
11311284 let Some(monitor) = self.active_monitor() else {
11321285 return;
@@ -1148,6 +1301,12 @@ impl<W: LayoutElement> Layout<W> {
11481301 monitor.move_column_to_workspace(idx);
11491302 }
11501303
1304+ pub fn move_column_to_workspace_on_output(&mut self, output: &Output, idx: usize) {
1305+ self.move_to_output(output);
1306+ self.focus_output(output);
1307+ self.move_column_to_workspace(idx);
1308+ }
1309+
11511310 pub fn switch_workspace_up(&mut self) {
11521311 let Some(monitor) = self.active_monitor() else {
11531312 return;
@@ -1257,6 +1416,7 @@ impl<W: LayoutElement> Layout<W> {
12571416 use crate::layout::monitor::WorkspaceSwitch;
12581417
12591418 let mut seen_workspace_id = HashSet::new();
1419+ let mut seen_workspace_name = HashSet::new();
12601420
12611421 let (monitors, &primary_idx, &active_monitor_idx) = match &self.monitor_set {
12621422 MonitorSet::Normal {
@@ -1267,8 +1427,8 @@ impl<W: LayoutElement> Layout<W> {
12671427 MonitorSet::NoOutputs { workspaces } => {
12681428 for workspace in workspaces {
12691429 assert!(
1270- workspace.has_windows(),
1271- "with no outputs there cannot be empty workspaces"
1430+ workspace.has_windows() || workspace.name.is_some(),
1431+ "with no outputs there cannot be empty unnamed workspaces"
12721432 );
12731433
12741434 assert_eq!(
@@ -1281,6 +1441,13 @@ impl<W: LayoutElement> Layout<W> {
12811441 "workspace id must be unique"
12821442 );
12831443
1444+ if let Some(name) = &workspace.name {
1445+ assert!(
1446+ seen_workspace_name.insert(name),
1447+ "workspace name must be unique"
1448+ );
1449+ }
1450+
12841451 workspace.verify_invariants();
12851452 }
12861453
@@ -1343,14 +1510,19 @@ impl<W: LayoutElement> Layout<W> {
13431510 "monitor must have an empty workspace in the end"
13441511 );
13451512
1513+ assert!(
1514+ monitor.workspaces.last().unwrap().name.is_none(),
1515+ "monitor must have an unnamed workspace in the end"
1516+ );
1517+
13461518 // If there's no workspace switch in progress, there can't be any non-last non-active
13471519 // empty workspaces.
13481520 if monitor.workspace_switch.is_none() {
13491521 for (idx, ws) in monitor.workspaces.iter().enumerate().rev().skip(1) {
13501522 if idx != monitor.active_workspace_idx {
13511523 assert!(
1352- !ws.columns.is_empty(),
1353- "non-active workspace can't be empty except the last one"
1524+ !ws.columns.is_empty() || ws.name.is_some(),
1525+ "non-active workspace can't be empty and unnamed except the last one"
13541526 );
13551527 }
13561528 }
@@ -1370,6 +1542,13 @@ impl<W: LayoutElement> Layout<W> {
13701542 "workspace id must be unique"
13711543 );
13721544
1545+ if let Some(name) = &workspace.name {
1546+ assert!(
1547+ seen_workspace_name.insert(name),
1548+ "workspace name must be unique"
1549+ );
1550+ }
1551+
13731552 workspace.verify_invariants();
13741553 }
13751554 }
@@ -1448,6 +1627,48 @@ impl<W: LayoutElement> Layout<W> {
14481627 }
14491628 }
14501629
1630+ pub fn ensure_named_workspace(&mut self, ws_config: &WorkspaceConfig) {
1631+ if self.find_workspace_by_name(&ws_config.name.0).is_some() {
1632+ return;
1633+ }
1634+
1635+ let options = self.options.clone();
1636+
1637+ match &mut self.monitor_set {
1638+ MonitorSet::Normal {
1639+ monitors,
1640+ primary_idx,
1641+ active_monitor_idx,
1642+ } => {
1643+ let mon_idx = ws_config
1644+ .open_on_output
1645+ .as_deref()
1646+ .map(|name| {
1647+ monitors
1648+ .iter_mut()
1649+ .position(|monitor| monitor.output.name().eq_ignore_ascii_case(name))
1650+ .unwrap_or(*primary_idx)
1651+ })
1652+ .unwrap_or(*active_monitor_idx);
1653+ let mon = &mut monitors[mon_idx];
1654+
1655+ let ws = Workspace::new_with_config(
1656+ mon.output.clone(),
1657+ Some(ws_config.clone()),
1658+ options,
1659+ );
1660+ mon.workspaces.insert(0, ws);
1661+ mon.active_workspace_idx += 1;
1662+ mon.workspace_switch = None;
1663+ mon.clean_up_workspaces();
1664+ }
1665+ MonitorSet::NoOutputs { workspaces } => {
1666+ let ws = Workspace::new_with_config_no_outputs(Some(ws_config.clone()), options);
1667+ workspaces.insert(0, ws);
1668+ }
1669+ }
1670+ }
1671+
14511672 pub fn update_config(&mut self, config: &Config) {
14521673 let options = Rc::new(Options::from_config(config));
14531674
@@ -2053,6 +2274,7 @@ impl<W: LayoutElement> Default for MonitorSet<W> {
20532274 mod tests {
20542275 use std::cell::Cell;
20552276
2277+ use niri_config::WorkspaceName;
20562278 use proptest::prelude::*;
20572279 use proptest_derive::Arbitrary;
20582280 use smithay::output::{Mode, PhysicalProperties, Subpixel};
@@ -2284,6 +2506,16 @@ mod tests {
22842506 AddOutput(#[proptest(strategy = "1..=5usize")] usize),
22852507 RemoveOutput(#[proptest(strategy = "1..=5usize")] usize),
22862508 FocusOutput(#[proptest(strategy = "1..=5usize")] usize),
2509+ AddNamedWorkspace {
2510+ #[proptest(strategy = "1..=5usize")]
2511+ ws_name: usize,
2512+ #[proptest(strategy = "prop::option::of(1..=5usize)")]
2513+ output_name: Option<usize>,
2514+ },
2515+ UnnameWorkspace {
2516+ #[proptest(strategy = "1..=5usize")]
2517+ ws_name: usize,
2518+ },
22872519 AddWindow {
22882520 #[proptest(strategy = "1..=5usize")]
22892521 id: usize,
@@ -2302,6 +2534,16 @@ mod tests {
23022534 #[proptest(strategy = "arbitrary_min_max_size()")]
23032535 min_max_size: (Size<i32, Logical>, Size<i32, Logical>),
23042536 },
2537+ AddWindowToNamedWorkspace {
2538+ #[proptest(strategy = "1..=5usize")]
2539+ id: usize,
2540+ #[proptest(strategy = "1..=5usize")]
2541+ ws_name: usize,
2542+ #[proptest(strategy = "arbitrary_bbox()")]
2543+ bbox: Rectangle<i32, Logical>,
2544+ #[proptest(strategy = "arbitrary_min_max_size()")]
2545+ min_max_size: (Size<i32, Logical>, Size<i32, Logical>),
2546+ },
23052547 CloseWindow(#[proptest(strategy = "1..=5usize")] usize),
23062548 FullscreenWindow(#[proptest(strategy = "1..=5usize")] usize),
23072549 FocusColumnLeft,
@@ -2438,6 +2680,18 @@ mod tests {
24382680
24392681 layout.focus_output(&output);
24402682 }
2683+ Op::AddNamedWorkspace {
2684+ ws_name,
2685+ output_name,
2686+ } => {
2687+ layout.ensure_named_workspace(&WorkspaceConfig {
2688+ name: WorkspaceName(format!("ws{ws_name}")),
2689+ open_on_output: output_name.map(|name| format!("output{name}")),
2690+ });
2691+ }
2692+ Op::UnnameWorkspace { ws_name } => {
2693+ layout.unname_workspace(&format!("ws{ws_name}"));
2694+ }
24412695 Op::AddWindow {
24422696 id,
24432697 bbox,
@@ -2515,6 +2769,53 @@ mod tests {
25152769 let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1);
25162770 layout.add_window_right_of(&right_of_id, win, None, false);
25172771 }
2772+ Op::AddWindowToNamedWorkspace {
2773+ id,
2774+ ws_name,
2775+ bbox,
2776+ min_max_size,
2777+ } => {
2778+ let ws_name = format!("ws{ws_name}");
2779+ let mut found_workspace = false;
2780+
2781+ match &mut layout.monitor_set {
2782+ MonitorSet::Normal { monitors, .. } => {
2783+ for mon in monitors {
2784+ for ws in &mut mon.workspaces {
2785+ for win in ws.windows() {
2786+ if win.0.id == id {
2787+ return;
2788+ }
2789+ }
2790+
2791+ if ws.name.as_deref() == Some(&ws_name) {
2792+ found_workspace = true;
2793+ }
2794+ }
2795+ }
2796+ }
2797+ MonitorSet::NoOutputs { workspaces, .. } => {
2798+ for ws in workspaces {
2799+ for win in ws.windows() {
2800+ if win.0.id == id {
2801+ return;
2802+ }
2803+ }
2804+
2805+ if ws.name.as_deref() == Some(&ws_name) {
2806+ found_workspace = true;
2807+ }
2808+ }
2809+ }
2810+ }
2811+
2812+ if !found_workspace {
2813+ return;
2814+ }
2815+
2816+ let win = TestWindow::new(id, bbox, min_max_size.0, min_max_size.1);
2817+ layout.add_window_to_named_workspace(&ws_name, win, None, false);
2818+ }
25182819 Op::CloseWindow(id) => {
25192820 layout.remove_window(&id);
25202821 }
@@ -2702,6 +3003,11 @@ mod tests {
27023003 Op::FocusOutput(0),
27033004 Op::FocusOutput(1),
27043005 Op::FocusOutput(2),
3006+ Op::AddNamedWorkspace {
3007+ ws_name: 1,
3008+ output_name: Some(1),
3009+ },
3010+ Op::UnnameWorkspace { ws_name: 1 },
27053011 Op::AddWindow {
27063012 id: 0,
27073013 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
@@ -2712,20 +3018,15 @@ mod tests {
27123018 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
27133019 min_max_size: Default::default(),
27143020 },
2715- Op::AddWindow {
3021+ Op::AddWindowRightOf {
27163022 id: 2,
3023+ right_of_id: 1,
27173024 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
27183025 min_max_size: Default::default(),
27193026 },
2720- Op::AddWindowRightOf {
3027+ Op::AddWindowToNamedWorkspace {
27213028 id: 3,
2722- right_of_id: 0,
2723- bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
2724- min_max_size: Default::default(),
2725- },
2726- Op::AddWindowRightOf {
2727- id: 4,
2728- right_of_id: 1,
3029+ ws_name: 1,
27293030 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
27303031 min_max_size: Default::default(),
27313032 },
@@ -2750,17 +3051,14 @@ mod tests {
27503051 Op::FocusWorkspaceUp,
27513052 Op::FocusWorkspace(1),
27523053 Op::FocusWorkspace(2),
2753- Op::FocusWorkspace(3),
27543054 Op::MoveWindowToWorkspaceDown,
27553055 Op::MoveWindowToWorkspaceUp,
27563056 Op::MoveWindowToWorkspace(1),
27573057 Op::MoveWindowToWorkspace(2),
2758- Op::MoveWindowToWorkspace(3),
27593058 Op::MoveColumnToWorkspaceDown,
27603059 Op::MoveColumnToWorkspaceUp,
27613060 Op::MoveColumnToWorkspace(1),
27623061 Op::MoveColumnToWorkspace(2),
2763- Op::MoveColumnToWorkspace(3),
27643062 Op::MoveWindowDown,
27653063 Op::MoveWindowDownOrToWorkspaceDown,
27663064 Op::MoveWindowUp,
@@ -2847,6 +3145,11 @@ mod tests {
28473145 Op::FocusOutput(0),
28483146 Op::FocusOutput(1),
28493147 Op::FocusOutput(2),
3148+ Op::AddNamedWorkspace {
3149+ ws_name: 1,
3150+ output_name: Some(1),
3151+ },
3152+ Op::UnnameWorkspace { ws_name: 1 },
28503153 Op::AddWindow {
28513154 id: 0,
28523155 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
@@ -2874,6 +3177,12 @@ mod tests {
28743177 bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
28753178 min_max_size: Default::default(),
28763179 },
3180+ Op::AddWindowToNamedWorkspace {
3181+ id: 5,
3182+ ws_name: 1,
3183+ bbox: Rectangle::from_loc_and_size((0, 0), (100, 200)),
3184+ min_max_size: Default::default(),
3185+ },
28773186 Op::CloseWindow(0),
28783187 Op::CloseWindow(1),
28793188 Op::CloseWindow(2),
src/layout/monitor.rsmodified+23 -1
@@ -103,6 +103,18 @@ impl<W: LayoutElement> Monitor<W> {
103103 &self.workspaces[self.active_workspace_idx]
104104 }
105105
106+ pub fn find_named_workspace(&self, workspace_name: &str) -> Option<&Workspace<W>> {
107+ self.workspaces
108+ .iter()
109+ .find(|w| w.name.as_deref() == Some(workspace_name))
110+ }
111+
112+ pub fn find_named_workspace_index(&self, workspace_name: &str) -> Option<usize> {
113+ self.workspaces
114+ .iter()
115+ .position(|w| w.name.as_deref() == Some(workspace_name))
116+ }
117+
106118 pub fn active_workspace(&mut self) -> &mut Workspace<W> {
107119 &mut self.workspaces[self.active_workspace_idx]
108120 }
@@ -204,7 +216,7 @@ impl<W: LayoutElement> Monitor<W> {
204216 continue;
205217 }
206218
207- if !self.workspaces[idx].has_windows() {
219+ if !self.workspaces[idx].has_windows() && self.workspaces[idx].name.is_none() {
208220 self.workspaces.remove(idx);
209221 if self.active_workspace_idx > idx {
210222 self.active_workspace_idx -= 1;
@@ -213,6 +225,16 @@ impl<W: LayoutElement> Monitor<W> {
213225 }
214226 }
215227
228+ pub fn unname_workspace(&mut self, workspace_name: &str) -> bool {
229+ for ws in &mut self.workspaces {
230+ if ws.name.as_deref() == Some(workspace_name) {
231+ ws.unname();
232+ return true;
233+ }
234+ }
235+ false
236+ }
237+
216238 pub fn move_left(&mut self) {
217239 self.active_workspace().move_left();
218240 }
src/layout/workspace.rsmodified+44 -4
@@ -3,7 +3,7 @@ use std::iter::{self, zip};
33 use std::rc::Rc;
44 use std::time::Duration;
55
6-use niri_config::{CenterFocusedColumn, PresetWidth, Struts};
6+use niri_config::{CenterFocusedColumn, PresetWidth, Struts, Workspace as WorkspaceConfig};
77 use niri_ipc::SizeChange;
88 use smithay::backend::renderer::gles::GlesRenderer;
99 use smithay::desktop::{layer_map_for_output, Window};
@@ -94,6 +94,9 @@ pub struct Workspace<W: LayoutElement> {
9494 /// Configurable properties of the layout.
9595 pub options: Rc<Options>,
9696
97+ /// Optional name of this workspace.
98+ pub name: Option<String>,
99+
97100 /// Unique ID of this workspace.
98101 id: WorkspaceId,
99102 }
@@ -313,9 +316,23 @@ impl TileData {
313316
314317 impl<W: LayoutElement> Workspace<W> {
315318 pub fn new(output: Output, options: Rc<Options>) -> Self {
319+ Self::new_with_config(output, None, options)
320+ }
321+
322+ pub fn new_with_config(
323+ output: Output,
324+ config: Option<WorkspaceConfig>,
325+ options: Rc<Options>,
326+ ) -> Self {
327+ let original_output = config
328+ .as_ref()
329+ .and_then(|c| c.open_on_output.clone())
330+ .map(OutputId)
331+ .unwrap_or(OutputId::new(&output));
332+
316333 let working_area = compute_working_area(&output, options.struts);
317334 Self {
318- original_output: OutputId::new(&output),
335+ original_output,
319336 view_size: output_size(&output),
320337 working_area,
321338 output: Some(output),
@@ -329,14 +346,24 @@ impl<W: LayoutElement> Workspace<W> {
329346 view_offset_before_fullscreen: None,
330347 closing_windows: vec![],
331348 options,
349+ name: config.map(|c| c.name.0),
332350 id: WorkspaceId::next(),
333351 }
334352 }
335353
336- pub fn new_no_outputs(options: Rc<Options>) -> Self {
354+ pub fn new_with_config_no_outputs(
355+ config: Option<WorkspaceConfig>,
356+ options: Rc<Options>,
357+ ) -> Self {
358+ let original_output = OutputId(
359+ config
360+ .clone()
361+ .and_then(|c| c.open_on_output)
362+ .unwrap_or_default(),
363+ );
337364 Self {
338365 output: None,
339- original_output: OutputId(String::new()),
366+ original_output,
340367 view_size: Size::from((1280, 720)),
341368 working_area: Rectangle::from_loc_and_size((0, 0), (1280, 720)),
342369 columns: vec![],
@@ -349,14 +376,23 @@ impl<W: LayoutElement> Workspace<W> {
349376 view_offset_before_fullscreen: None,
350377 closing_windows: vec![],
351378 options,
379+ name: config.map(|c| c.name.0),
352380 id: WorkspaceId::next(),
353381 }
354382 }
355383
384+ pub fn new_no_outputs(options: Rc<Options>) -> Self {
385+ Self::new_with_config_no_outputs(None, options)
386+ }
387+
356388 pub fn id(&self) -> WorkspaceId {
357389 self.id
358390 }
359391
392+ pub fn unname(&mut self) {
393+ self.name = None;
394+ }
395+
360396 pub fn advance_animations(&mut self, current_time: Duration) {
361397 if let Some(ViewOffsetAdjustment::Animation(anim)) = &mut self.view_offset_adj {
362398 anim.set_current_time(current_time);
@@ -435,6 +471,10 @@ impl<W: LayoutElement> Workspace<W> {
435471 .map(Tile::window_mut)
436472 }
437473
474+ pub fn current_output(&self) -> Option<&Output> {
475+ self.output.as_ref()
476+ }
477+
438478 pub fn set_output(&mut self, output: Option<Output>) {
439479 if self.output == output {
440480 return;
src/niri.rsmodified+49 -1
@@ -11,7 +11,7 @@ use std::{env, mem, thread};
1111 use _server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as KdeDecorationsMode;
1212 use anyhow::{ensure, Context};
1313 use calloop::futures::Scheduler;
14-use niri_config::{Config, Key, Modifiers, PreviewRender, TrackLayout};
14+use niri_config::{Config, Key, Modifiers, PreviewRender, TrackLayout, WorkspaceReference};
1515 use smithay::backend::allocator::Fourcc;
1616 use smithay::backend::renderer::damage::OutputDamageTracker;
1717 use smithay::backend::renderer::element::memory::MemoryRenderBufferRenderElement;
@@ -857,8 +857,24 @@ impl State {
857857
858858 self.niri.config_error_notification.hide();
859859
860+ // Find & orphan removed named workspaces.
861+ let mut removed_workspaces: Vec<String> = vec![];
862+ for ws in &self.niri.config.borrow().workspaces {
863+ if !config.workspaces.iter().any(|w| w.name == ws.name) {
864+ removed_workspaces.push(ws.name.0.clone());
865+ }
866+ }
867+ for name in removed_workspaces {
868+ self.niri.layout.unname_workspace(&name);
869+ }
870+
860871 self.niri.layout.update_config(&config);
861872
873+ // Create new named workspaces.
874+ for ws_config in &config.workspaces {
875+ self.niri.layout.ensure_named_workspace(ws_config);
876+ }
877+
862878 let slowdown = if config.animations.off {
863879 0.
864880 } else {
@@ -2097,6 +2113,38 @@ impl Niri {
20972113 .cloned()
20982114 }
20992115
2116+ pub fn output_by_name(&self, name: &str) -> Option<Output> {
2117+ self.global_space
2118+ .outputs()
2119+ .find(|output| output.name().eq_ignore_ascii_case(name))
2120+ .cloned()
2121+ }
2122+
2123+ pub fn find_output_and_workspace_index(
2124+ &self,
2125+ workspace_reference: WorkspaceReference,
2126+ ) -> Option<(Option<Output>, usize)> {
2127+ let workspace_name = match workspace_reference {
2128+ WorkspaceReference::Index(index) => {
2129+ return Some((None, index.saturating_sub(1) as usize));
2130+ }
2131+ WorkspaceReference::Name(name) => name,
2132+ };
2133+
2134+ let (target_workspace_index, target_workspace) =
2135+ self.layout.find_workspace_by_name(&workspace_name)?;
2136+
2137+ // FIXME: when we do fixes for no connected outputs, this will need fixing too.
2138+ let active_workspace = self.layout.active_workspace()?;
2139+
2140+ if target_workspace.current_output() == active_workspace.current_output() {
2141+ return Some((None, target_workspace_index));
2142+ }
2143+ let target_output = target_workspace.current_output()?;
2144+
2145+ Some((Some(target_output.clone()), target_workspace_index))
2146+ }
2147+
21002148 pub fn output_down(&self) -> Option<Output> {
21012149 let active = self.layout.active_output()?;
21022150 let active_geo = self.global_space.output_geometry(active).unwrap();
src/window/mod.rsmodified+10 -0
@@ -33,6 +33,9 @@ pub struct ResolvedWindowRules {
3333 /// Output to open this window on.
3434 pub open_on_output: Option<String>,
3535
36+ /// Workspace to open this window on.
37+ pub open_on_workspace: Option<String>,
38+
3639 /// Whether the window should open full-width.
3740 pub open_maximized: Option<bool>,
3841
@@ -99,6 +102,7 @@ impl ResolvedWindowRules {
99102 Self {
100103 default_width: None,
101104 open_on_output: None,
105+ open_on_workspace: None,
102106 open_maximized: None,
103107 open_fullscreen: None,
104108 min_width: None,
@@ -151,6 +155,7 @@ impl ResolvedWindowRules {
151155 }
152156
153157 let mut open_on_output = None;
158+ let mut open_on_workspace = None;
154159
155160 for rule in rules {
156161 let matches = |m| window_matches(window, &role, m);
@@ -175,6 +180,10 @@ impl ResolvedWindowRules {
175180 open_on_output = Some(x);
176181 }
177182
183+ if let Some(x) = rule.open_on_workspace.as_deref() {
184+ open_on_workspace = Some(x);
185+ }
186+
178187 if let Some(x) = rule.open_maximized {
179188 resolved.open_maximized = Some(x);
180189 }
@@ -217,6 +226,7 @@ impl ResolvedWindowRules {
217226 }
218227
219228 resolved.open_on_output = open_on_output.map(|x| x.to_owned());
229+ resolved.open_on_workspace = open_on_workspace.map(|x| x.to_owned());
220230 });
221231
222232 resolved
src/window/unmapped.rsmodified+4 -0
@@ -11,6 +11,7 @@ pub struct Unmapped {
1111 pub state: InitialConfigureState,
1212 }
1313
14+#[allow(clippy::large_enum_variant)]
1415 #[derive(Debug)]
1516 pub enum InitialConfigureState {
1617 /// The window has not been initially configured yet.
@@ -42,6 +43,9 @@ pub enum InitialConfigureState {
4243 /// - This is a dialog with a parent, and there was no explicit output set, so this dialog
4344 /// should fetch the parent's current output again upon mapping.
4445 output: Option<Output>,
46+
47+ /// Workspace to open this window on.
48+ workspace_name: Option<String>,
4549 },
4650 }
4751