forge
Explore
Log in

Don't you dare go Hollow

Add spawn-sh, spawn-at-startup-sh

Browse files at this commit

e81f356908fe38ec45c74cf822dd102efbcf6457Ivan MolodetskikhParent: 1013147
Our top 10 most confusing config moments
docs/wiki/Configuration:-Key-Bindings.mdmodified+33 -1
@@ -206,7 +206,8 @@ binds {
206 > }206 > }
207 > ```207 > ```
208 208
209-Currently, niri *does not* use a shell to run commands, which means that you need to manually separate arguments.209+For `spawn`, niri *does not* use a shell to run commands, which means that you need to manually separate arguments.
210+See [`spawn-sh`](#spawn-sh) below for an action that uses a shell.
210 211
211 ```kdl212 ```kdl
212 binds {213 binds {
@@ -249,6 +250,37 @@ binds {
249 }250 }
250 ```251 ```
251 252
253+#### `spawn-sh`
254+
255+<sup>Since: next release</sup>
256+
257+Run a command through the shell.
258+
259+The argument is a single string that is passed verbatim to `sh`.
260+You can use shell variables, pipelines, `~` expansion, and everything else as expected.
261+
262+```kdl
263+binds {
264+ // Works with spawn-sh: all arguments in the same string.
265+ Mod+D { spawn-sh "alacritty -e /usr/bin/fish"; }
266+
267+ // Works with spawn-sh: shell variable ($MAIN_OUTPUT), ~ expansion.
268+ Mod+T { spawn-sh "grim -o $MAIN_OUTPUT ~/screenshot.png"; }
269+
270+ // Works with spawn-sh: process substitution.
271+ Mod+Q { spawn-sh "notify-send clipboard \"$(wl-paste)\""; }
272+
273+ // Works with spawn-sh: multiple commands.
274+ Super+Alt+S { spawn-sh "pkill orca || exec orca"; }
275+}
276+```
277+
278+`spawn-sh "some command"` is equivalent to `spawn "sh" "-c" "some command"`—it's just a less confusing shorthand.
279+Keep in mind that going through the shell incurs a tiny performance penalty compared to directly `spawn`ing some binary.
280+
281+Using `sh` is hardcoded, consistent with other compositors.
282+If you want a different shell, write it out using `spawn`, e.g. `spawn "fish" "-c" "some fish command"`.
283+
252 #### `quit`284 #### `quit`
253 285
254 Exit niri after showing a confirmation dialog to avoid accidentally triggering it.286 Exit niri after showing a confirmation dialog to avoid accidentally triggering it.
docs/wiki/Configuration:-Miscellaneous.mdmodified+17 -0
@@ -5,6 +5,7 @@ Here are all of these options at a glance:
5 ```kdl5 ```kdl
6 spawn-at-startup "waybar"6 spawn-at-startup "waybar"
7 spawn-at-startup "alacritty"7 spawn-at-startup "alacritty"
8+spawn-at-startup-sh "qs -c ~/source/qs/MyAwesomeShell"
8 9
9 prefer-no-csd10 prefer-no-csd
10 11
@@ -71,6 +72,22 @@ spawn-at-startup "alacritty"
71 Note that running niri as a systemd session supports xdg-desktop-autostart out of the box, which may be more convenient to use.72 Note that running niri as a systemd session supports xdg-desktop-autostart out of the box, which may be more convenient to use.
72 Thanks to this, apps that you configured to autostart in GNOME will also "just work" in niri, without any manual `spawn-at-startup` configuration.73 Thanks to this, apps that you configured to autostart in GNOME will also "just work" in niri, without any manual `spawn-at-startup` configuration.
73 74
75+### `spawn-at-startup-sh`
76+
77+<sup>Since: next release</sup>
78+
79+Add lines like this to run shell commands at niri startup.
80+
81+The argument is a single string that is passed verbatim to `sh`.
82+You can use shell variables, pipelines, `~` expansion and everything else as expected.
83+
84+See detailed description in the docs for the [`spawn-sh` key binding action](./Configuration:-Key-Bindings.md#spawn-sh).
85+
86+```kdl
87+// Pass all arguments in the same string.
88+spawn-at-startup-sh "qs -c ~/source/qs/MyAwesomeShell"
89+```
90+
74 ### `prefer-no-csd`91 ### `prefer-no-csd`
75 92
76 This flag will make niri ask the applications to omit their client-side decorations.93 This flag will make niri ask the applications to omit their client-side decorations.
niri-config/src/lib.rsmodified+36 -1
@@ -41,6 +41,8 @@ pub struct Config {
41 pub outputs: Outputs,41 pub outputs: Outputs,
42 #[knuffel(children(name = "spawn-at-startup"))]42 #[knuffel(children(name = "spawn-at-startup"))]
43 pub spawn_at_startup: Vec<SpawnAtStartup>,43 pub spawn_at_startup: Vec<SpawnAtStartup>,
44+ #[knuffel(children(name = "spawn-at-startup-sh"))]
45+ pub spawn_at_startup_sh: Vec<SpawnAtStartupSh>,
44 #[knuffel(child, default)]46 #[knuffel(child, default)]
45 pub layout: Layout,47 pub layout: Layout,
46 #[knuffel(child, default)]48 #[knuffel(child, default)]
@@ -606,6 +608,12 @@ pub struct SpawnAtStartup {
606 pub command: Vec<String>,608 pub command: Vec<String>,
607 }609 }
608 610
611+#[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)]
612+pub struct SpawnAtStartupSh {
613+ #[knuffel(argument)]
614+ pub command: String,
615+}
616+
609 #[derive(knuffel::Decode, Debug, Clone, Copy, PartialEq)]617 #[derive(knuffel::Decode, Debug, Clone, Copy, PartialEq)]
610 pub struct FocusRing {618 pub struct FocusRing {
611 #[knuffel(child)]619 #[knuffel(child)]
@@ -1719,6 +1727,7 @@ pub enum Action {
1719 DebugToggleOpaqueRegions,1727 DebugToggleOpaqueRegions,
1720 DebugToggleDamage,1728 DebugToggleDamage,
1721 Spawn(#[knuffel(arguments)] Vec<String>),1729 Spawn(#[knuffel(arguments)] Vec<String>),
1730+ SpawnSh(#[knuffel(argument)] String),
1722 DoScreenTransition(#[knuffel(property(name = "delay-ms"))] Option<u16>),1731 DoScreenTransition(#[knuffel(property(name = "delay-ms"))] Option<u16>),
1723 #[knuffel(skip)]1732 #[knuffel(skip)]
1724 ConfirmScreenshot {1733 ConfirmScreenshot {
@@ -1962,6 +1971,7 @@ impl From<niri_ipc::Action> for Action {
1962 niri_ipc::Action::PowerOffMonitors {} => Self::PowerOffMonitors,1971 niri_ipc::Action::PowerOffMonitors {} => Self::PowerOffMonitors,
1963 niri_ipc::Action::PowerOnMonitors {} => Self::PowerOnMonitors,1972 niri_ipc::Action::PowerOnMonitors {} => Self::PowerOnMonitors,
1964 niri_ipc::Action::Spawn { command } => Self::Spawn(command),1973 niri_ipc::Action::Spawn { command } => Self::Spawn(command),
1974+ niri_ipc::Action::SpawnSh { command } => Self::SpawnSh(command),
1965 niri_ipc::Action::DoScreenTransition { delay_ms } => Self::DoScreenTransition(delay_ms),1975 niri_ipc::Action::DoScreenTransition { delay_ms } => Self::DoScreenTransition(delay_ms),
1966 niri_ipc::Action::Screenshot { show_pointer } => Self::Screenshot(show_pointer),1976 niri_ipc::Action::Screenshot { show_pointer } => Self::Screenshot(show_pointer),
1967 niri_ipc::Action::ScreenshotScreen {1977 niri_ipc::Action::ScreenshotScreen {
@@ -3854,7 +3864,7 @@ where
3854 }3864 }
3855 match Action::decode_node(child, ctx) {3865 match Action::decode_node(child, ctx) {
3856 Ok(action) => {3866 Ok(action) => {
3857- if !matches!(action, Action::Spawn(_)) {3867+ if !matches!(action, Action::Spawn(_) | Action::SpawnSh(_)) {
3858 if let Some(node) = allow_when_locked_node {3868 if let Some(node) = allow_when_locked_node {
3859 ctx.emit_error(DecodeError::unexpected(3869 ctx.emit_error(DecodeError::unexpected(
3860 node,3870 node,
@@ -4453,6 +4463,7 @@ mod tests {
4453 }4463 }
4454 4464
4455 spawn-at-startup "alacritty" "-e" "fish"4465 spawn-at-startup "alacritty" "-e" "fish"
4466+ spawn-at-startup-sh "qs -c ~/source/qs/MyAwesomeShell"
4456 4467
4457 prefer-no-csd4468 prefer-no-csd
4458 4469
@@ -4549,6 +4560,7 @@ mod tests {
4549 Mod+Shift+1 { focus-workspace "workspace-1"; }4560 Mod+Shift+1 { focus-workspace "workspace-1"; }
4550 Mod+Shift+E allow-inhibiting=false { quit skip-confirmation=true; }4561 Mod+Shift+E allow-inhibiting=false { quit skip-confirmation=true; }
4551 Mod+WheelScrollDown cooldown-ms=150 { focus-workspace-down; }4562 Mod+WheelScrollDown cooldown-ms=150 { focus-workspace-down; }
4563+ Super+Alt+S allow-when-locked=true { spawn-sh "pkill orca || exec orca"; }
4552 }4564 }
4553 4565
4554 switch-events {4566 switch-events {
@@ -4794,6 +4806,11 @@ mod tests {
4794 ],4806 ],
4795 },4807 },
4796 ],4808 ],
4809+ spawn_at_startup_sh: [
4810+ SpawnAtStartupSh {
4811+ command: "qs -c ~/source/qs/MyAwesomeShell",
4812+ },
4813+ ],
4797 layout: Layout {4814 layout: Layout {
4798 focus_ring: FocusRing {4815 focus_ring: FocusRing {
4799 off: false,4816 off: false,
@@ -5681,6 +5698,24 @@ mod tests {
5681 allow_inhibiting: true,5698 allow_inhibiting: true,
5682 hotkey_overlay_title: None,5699 hotkey_overlay_title: None,
5683 },5700 },
5701+ Bind {
5702+ key: Key {
5703+ trigger: Keysym(
5704+ XK_s,
5705+ ),
5706+ modifiers: Modifiers(
5707+ ALT | SUPER,
5708+ ),
5709+ },
5710+ action: SpawnSh(
5711+ "pkill orca || exec orca",
5712+ ),
5713+ repeat: true,
5714+ cooldown: None,
5715+ allow_when_locked: true,
5716+ allow_inhibiting: true,
5717+ hotkey_overlay_title: None,
5718+ },
5684 ],5719 ],
5685 ),5720 ),
5686 switch_events: SwitchBinds {5721 switch_events: SwitchBinds {
niri-ipc/src/lib.rsmodified+6 -0
@@ -203,6 +203,12 @@ pub enum Action {
203 #[cfg_attr(feature = "clap", arg(last = true, required = true))]203 #[cfg_attr(feature = "clap", arg(last = true, required = true))]
204 command: Vec<String>,204 command: Vec<String>,
205 },205 },
206+ /// Spawn a command through the shell.
207+ SpawnSh {
208+ /// Command to run.
209+ #[cfg_attr(feature = "clap", arg(last = true, required = true))]
210+ command: String,
211+ },
206 /// Do a screen transition.212 /// Do a screen transition.
207 DoScreenTransition {213 DoScreenTransition {
208 /// Delay in milliseconds for the screen to freeze before starting the transition.214 /// Delay in milliseconds for the screen to freeze before starting the transition.
resources/default-config.kdlmodified+6 -3
@@ -270,6 +270,9 @@ layout {
270 // This line starts waybar, a commonly used bar for Wayland compositors.270 // This line starts waybar, a commonly used bar for Wayland compositors.
271 spawn-at-startup "waybar"271 spawn-at-startup "waybar"
272 272
273+// To run a shell command (with variables, pipes, etc.), use spawn-at-startup-sh:
274+// spawn-at-startup-sh "qs -c ~/source/qs/MyAwesomeShell"
275+
273 hotkey-overlay {276 hotkey-overlay {
274 // Uncomment this line to disable the "Important Hotkeys" pop-up at startup.277 // Uncomment this line to disable the "Important Hotkeys" pop-up at startup.
275 // skip-at-startup278 // skip-at-startup
@@ -363,10 +366,10 @@ binds {
363 Mod+D hotkey-overlay-title="Run an Application: fuzzel" { spawn "fuzzel"; }366 Mod+D hotkey-overlay-title="Run an Application: fuzzel" { spawn "fuzzel"; }
364 Super+Alt+L hotkey-overlay-title="Lock the Screen: swaylock" { spawn "swaylock"; }367 Super+Alt+L hotkey-overlay-title="Lock the Screen: swaylock" { spawn "swaylock"; }
365 368
366- // You can also use a shell. Do this if you need pipes, multiple commands, etc.369+ // Use spawn-sh to run a shell command. Do this if you need pipes, multiple commands, etc.
367- // Note: the entire command goes as a single argument in the end.370+ // Note: the entire command goes as a single argument. It's passed verbatim to `sh -c`.
368 // For example, this is a standard bind to toggle the screen reader (orca).371 // For example, this is a standard bind to toggle the screen reader (orca).
369- Super+Alt+S hotkey-overlay-title=null { spawn "sh" "-c" "pkill orca || exec orca"; }372+ Super+Alt+S hotkey-overlay-title=null { spawn-sh "pkill orca || exec orca"; }
370 373
371 // Example volume keys mappings for PipeWire & WirePlumber.374 // Example volume keys mappings for PipeWire & WirePlumber.
372 // The allow-when-locked=true property makes them work even when the session is locked.375 // The allow-when-locked=true property makes them work even when the session is locked.
src/input/mod.rsmodified+5 -1
@@ -44,7 +44,7 @@ use crate::layout::scrolling::ScrollDirection;
44 use crate::layout::{ActivateWindow, LayoutElement as _};44 use crate::layout::{ActivateWindow, LayoutElement as _};
45 use crate::niri::{CastTarget, PointerVisibility, State};45 use crate::niri::{CastTarget, PointerVisibility, State};
46 use crate::ui::screenshot_ui::ScreenshotUi;46 use crate::ui::screenshot_ui::ScreenshotUi;
47-use crate::utils::spawning::spawn;47+use crate::utils::spawning::{spawn, spawn_sh};
48 use crate::utils::{center, get_monotonic_time, ResizeEdge};48 use crate::utils::{center, get_monotonic_time, ResizeEdge};
49 49
50 pub mod backend_ext;50 pub mod backend_ext;
@@ -595,6 +595,10 @@ impl State {
595 let (token, _) = self.niri.activation_state.create_external_token(None);595 let (token, _) = self.niri.activation_state.create_external_token(None);
596 spawn(command, Some(token.clone()));596 spawn(command, Some(token.clone()));
597 }597 }
598+ Action::SpawnSh(command) => {
599+ let (token, _) = self.niri.activation_state.create_external_token(None);
600+ spawn_sh(command, Some(token.clone()));
601+ }
598 Action::DoScreenTransition(delay_ms) => {602 Action::DoScreenTransition(delay_ms) => {
599 self.backend.with_primary_renderer(|renderer| {603 self.backend.with_primary_renderer(|renderer| {
600 self.niri.do_screen_transition(renderer, delay_ms);604 self.niri.do_screen_transition(renderer, delay_ms);
src/main.rsmodified+6 -2
@@ -20,8 +20,8 @@ use niri::dbus;
20 use niri::ipc::client::handle_msg;20 use niri::ipc::client::handle_msg;
21 use niri::niri::State;21 use niri::niri::State;
22 use niri::utils::spawning::{22 use niri::utils::spawning::{
23- spawn, store_and_increase_nofile_rlimit, CHILD_DISPLAY, CHILD_ENV, REMOVE_ENV_RUST_BACKTRACE,23+ spawn, spawn_sh, store_and_increase_nofile_rlimit, CHILD_DISPLAY, CHILD_ENV,
24- REMOVE_ENV_RUST_LIB_BACKTRACE,24+ REMOVE_ENV_RUST_BACKTRACE, REMOVE_ENV_RUST_LIB_BACKTRACE,
25 };25 };
26 use niri::utils::{cause_panic, version, watcher, xwayland, IS_SYSTEMD_SERVICE};26 use niri::utils::{cause_panic, version, watcher, xwayland, IS_SYSTEMD_SERVICE};
27 use niri_config::ConfigPath;27 use niri_config::ConfigPath;
@@ -151,6 +151,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
151 .unwrap_or_default();151 .unwrap_or_default();
152 152
153 let spawn_at_startup = mem::take(&mut config.spawn_at_startup);153 let spawn_at_startup = mem::take(&mut config.spawn_at_startup);
154+ let spawn_at_startup_sh = mem::take(&mut config.spawn_at_startup_sh);
154 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);155 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);
155 156
156 store_and_increase_nofile_rlimit();157 store_and_increase_nofile_rlimit();
@@ -237,6 +238,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
237 for elem in spawn_at_startup {238 for elem in spawn_at_startup {
238 spawn(elem.command, None);239 spawn(elem.command, None);
239 }240 }
241+ for elem in spawn_at_startup_sh {
242+ spawn_sh(elem.command, None);
243+ }
240 244
241 // Show the config error notification right away if needed.245 // Show the config error notification right away if needed.
242 if config_errored {246 if config_errored {
src/ui/hotkey_overlay.rsmodified+6 -1
@@ -270,7 +270,7 @@ fn render(
270 270
271 // Add the spawn actions.271 // Add the spawn actions.
272 for bind in binds.iter().filter(|bind| {272 for bind in binds.iter().filter(|bind| {
273- matches!(bind.action, Action::Spawn(_))273+ matches!(bind.action, Action::Spawn(_) | Action::SpawnSh(_))
274 // Only show binds with Mod or Super to filter out stuff like volume up/down.274 // Only show binds with Mod or Super to filter out stuff like volume up/down.
275 && (bind.key.modifiers.contains(Modifiers::COMPOSITOR)275 && (bind.key.modifiers.contains(Modifiers::COMPOSITOR)
276 || bind.key.modifiers.contains(Modifiers::SUPER))276 || bind.key.modifiers.contains(Modifiers::SUPER))
@@ -447,6 +447,11 @@ fn action_name(action: &Action) -> String {
447 "Spawn <span face='monospace' bgcolor='#000000'>{}</span>",447 "Spawn <span face='monospace' bgcolor='#000000'>{}</span>",
448 args.first().unwrap_or(&String::new())448 args.first().unwrap_or(&String::new())
449 ),449 ),
450+ Action::SpawnSh(command) => format!(
451+ "Spawn <span face='monospace' bgcolor='#000000'>{}</span>",
452+ // Fairly crude but should get the job done in most cases.
453+ command.split_ascii_whitespace().next().unwrap_or("")
454+ ),
450 _ => String::from("FIXME: Unknown"),455 _ => String::from("FIXME: Unknown"),
451 }456 }
452 }457 }
src/utils/spawning.rsmodified+10 -0
@@ -83,6 +83,16 @@ pub fn spawn<T: AsRef<OsStr> + Send + 'static>(command: Vec<T>, token: Option<Xd
83 }83 }
84 }84 }
85 85
86+/// Spawns the command through the shell.
87+///
88+/// We hardcode `sh -c`, consistent with other compositors:
89+///
90+/// - https://github.com/swaywm/sway/blob/b3dcde8d69c3f1304b076968a7a64f54d0c958be/sway/commands/exec_always.c#L64
91+/// - https://github.com/hyprwm/Hyprland/blob/1ac1ff457ab8ef1ae6a8f2ab17ee7965adfa729f/src/managers/KeybindManager.cpp#L987
92+pub fn spawn_sh(command: String, token: Option<XdgActivationToken>) {
93+ spawn(vec![String::from("sh"), String::from("-c"), command], token);
94+}
95+
86 fn spawn_sync(96 fn spawn_sync(
87 command: impl AsRef<OsStr>,97 command: impl AsRef<OsStr>,
88 args: impl IntoIterator<Item = impl AsRef<OsStr>>,98 args: impl IntoIterator<Item = impl AsRef<OsStr>>,