forge
Explore
Log in

Don't you dare go Hollow

Add --path argument for niri msg screenshot* commands (#2126)

Browse files at this commit

23cd5aa78a26ccf57c6a7993313e42a5c39d43d8UnverifiedLin Xianyi and Ivan MolodetskikhParent: 8c84479
* Check for empty screenshot parent before creating

Avoids a warning.

* Add --path argument for niri msg screenshot* commands

* fix

---------
niri-config/src/binds.rsmodified+26 -6
@@ -118,16 +118,27 @@ pub enum Action {
118118 CancelScreenshot,
119119 #[knuffel(skip)]
120120 ScreenshotTogglePointer,
121- Screenshot(#[knuffel(property(name = "show-pointer"), default = true)] bool),
121+ Screenshot(
122+ #[knuffel(property(name = "show-pointer"), default = true)] bool,
123+ // Path; not settable from knuffel
124+ Option<String>,
125+ ),
122126 ScreenshotScreen(
123127 #[knuffel(property(name = "write-to-disk"), default = true)] bool,
124128 #[knuffel(property(name = "show-pointer"), default = true)] bool,
129+ // Path; not settable from knuffel
130+ Option<String>,
131+ ),
132+ ScreenshotWindow(
133+ #[knuffel(property(name = "write-to-disk"), default = true)] bool,
134+ // Path; not settable from knuffel
135+ Option<String>,
125136 ),
126- ScreenshotWindow(#[knuffel(property(name = "write-to-disk"), default = true)] bool),
127137 #[knuffel(skip)]
128138 ScreenshotWindowById {
129139 id: u64,
130140 write_to_disk: bool,
141+ path: Option<String>,
131142 },
132143 ToggleKeyboardShortcutsInhibit,
133144 CloseWindow,
@@ -364,19 +375,28 @@ impl From<niri_ipc::Action> for Action {
364375 niri_ipc::Action::Spawn { command } => Self::Spawn(command),
365376 niri_ipc::Action::SpawnSh { command } => Self::SpawnSh(command),
366377 niri_ipc::Action::DoScreenTransition { delay_ms } => Self::DoScreenTransition(delay_ms),
367- niri_ipc::Action::Screenshot { show_pointer } => Self::Screenshot(show_pointer),
378+ niri_ipc::Action::Screenshot { show_pointer, path } => {
379+ Self::Screenshot(show_pointer, path)
380+ }
368381 niri_ipc::Action::ScreenshotScreen {
369382 write_to_disk,
370383 show_pointer,
371- } => Self::ScreenshotScreen(write_to_disk, show_pointer),
384+ path,
385+ } => Self::ScreenshotScreen(write_to_disk, show_pointer, path),
372386 niri_ipc::Action::ScreenshotWindow {
373387 id: None,
374388 write_to_disk,
375- } => Self::ScreenshotWindow(write_to_disk),
389+ path,
390+ } => Self::ScreenshotWindow(write_to_disk, path),
376391 niri_ipc::Action::ScreenshotWindow {
377392 id: Some(id),
378393 write_to_disk,
379- } => Self::ScreenshotWindowById { id, write_to_disk },
394+ path,
395+ } => Self::ScreenshotWindowById {
396+ id,
397+ write_to_disk,
398+ path,
399+ },
380400 niri_ipc::Action::ToggleKeyboardShortcutsInhibit {} => {
381401 Self::ToggleKeyboardShortcutsInhibit
382402 }
niri-ipc/src/lib.rsmodified+24 -0
@@ -220,6 +220,14 @@ pub enum Action {
220220 /// Whether to show the mouse pointer by default in the screenshot UI.
221221 #[cfg_attr(feature = "clap", arg(short = 'p', long, action = clap::ArgAction::Set, default_value_t = true))]
222222 show_pointer: bool,
223+
224+ /// Path to save the screenshot to.
225+ ///
226+ /// The path must be absolute, otherwise an error is returned.
227+ ///
228+ /// If `None`, the screenshot is saved according to the `screenshot-path` config setting.
229+ #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set))]
230+ path: Option<String>,
223231 },
224232 /// Screenshot the focused screen.
225233 ScreenshotScreen {
@@ -232,6 +240,14 @@ pub enum Action {
232240 /// Whether to include the mouse pointer in the screenshot.
233241 #[cfg_attr(feature = "clap", arg(short = 'p', long, action = clap::ArgAction::Set, default_value_t = true))]
234242 show_pointer: bool,
243+
244+ /// Path to save the screenshot to.
245+ ///
246+ /// The path must be absolute, otherwise an error is returned.
247+ ///
248+ /// If `None`, the screenshot is saved according to the `screenshot-path` config setting.
249+ #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set))]
250+ path: Option<String>,
235251 },
236252 /// Screenshot a window.
237253 #[cfg_attr(feature = "clap", clap(about = "Screenshot the focused window"))]
@@ -246,6 +262,14 @@ pub enum Action {
246262 /// The screenshot is saved according to the `screenshot-path` config setting.
247263 #[cfg_attr(feature = "clap", arg(short = 'd', long, action = clap::ArgAction::Set, default_value_t = true))]
248264 write_to_disk: bool,
265+
266+ /// Path to save the screenshot to.
267+ ///
268+ /// The path must be absolute, otherwise an error is returned.
269+ ///
270+ /// If `None`, the screenshot is saved according to the `screenshot-path` config setting.
271+ #[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Set))]
272+ path: Option<String>,
249273 },
250274 /// Enable or disable the keyboard shortcuts inhibitor (if any) for the focused surface.
251275 ToggleKeyboardShortcutsInhibit {},
src/input/mod.rsmodified+30 -17
@@ -605,14 +605,17 @@ impl State {
605605 self.niri.do_screen_transition(renderer, delay_ms);
606606 });
607607 }
608- Action::ScreenshotScreen(write_to_disk, show_pointer) => {
608+ Action::ScreenshotScreen(write_to_disk, show_pointer, path) => {
609609 let active = self.niri.layout.active_output().cloned();
610610 if let Some(active) = active {
611611 self.backend.with_primary_renderer(|renderer| {
612- if let Err(err) =
613- self.niri
614- .screenshot(renderer, &active, write_to_disk, show_pointer)
615- {
612+ if let Err(err) = self.niri.screenshot(
613+ renderer,
614+ &active,
615+ write_to_disk,
616+ show_pointer,
617+ path,
618+ ) {
616619 warn!("error taking screenshot: {err:?}");
617620 }
618621 });
@@ -636,32 +639,42 @@ impl State {
636639 self.niri.screenshot_ui.toggle_pointer();
637640 self.niri.queue_redraw_all();
638641 }
639- Action::Screenshot(show_cursor) => {
640- self.open_screenshot_ui(show_cursor);
642+ Action::Screenshot(show_cursor, path) => {
643+ self.open_screenshot_ui(show_cursor, path);
641644 }
642- Action::ScreenshotWindow(write_to_disk) => {
645+ Action::ScreenshotWindow(write_to_disk, path) => {
643646 let focus = self.niri.layout.focus_with_output();
644647 if let Some((mapped, output)) = focus {
645648 self.backend.with_primary_renderer(|renderer| {
646- if let Err(err) =
647- self.niri
648- .screenshot_window(renderer, output, mapped, write_to_disk)
649- {
649+ if let Err(err) = self.niri.screenshot_window(
650+ renderer,
651+ output,
652+ mapped,
653+ write_to_disk,
654+ path,
655+ ) {
650656 warn!("error taking screenshot: {err:?}");
651657 }
652658 });
653659 }
654660 }
655- Action::ScreenshotWindowById { id, write_to_disk } => {
661+ Action::ScreenshotWindowById {
662+ id,
663+ write_to_disk,
664+ path,
665+ } => {
656666 let mut windows = self.niri.layout.windows();
657667 let window = windows.find(|(_, m)| m.id().get() == id);
658668 if let Some((Some(monitor), mapped)) = window {
659669 let output = monitor.output();
660670 self.backend.with_primary_renderer(|renderer| {
661- if let Err(err) =
662- self.niri
663- .screenshot_window(renderer, output, mapped, write_to_disk)
664- {
671+ if let Err(err) = self.niri.screenshot_window(
672+ renderer,
673+ output,
674+ mapped,
675+ write_to_disk,
676+ path,
677+ ) {
665678 warn!("error taking screenshot: {err:?}");
666679 }
667680 });
src/ipc/client.rsmodified+31 -4
@@ -1,20 +1,34 @@
11 use std::io::ErrorKind;
22 use std::iter::Peekable;
3-use std::slice;
3+use std::path::Path;
4+use std::{env, slice};
45
56 use anyhow::{anyhow, bail, Context};
67 use niri_config::OutputName;
78 use niri_ipc::socket::Socket;
89 use niri_ipc::{
9- Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Overview, Request,
10- Response, Transform, Window, WindowLayout,
10+ Action, Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Overview,
11+ Request, Response, Transform, Window, WindowLayout,
1112 };
1213 use serde_json::json;
1314
1415 use crate::cli::Msg;
1516 use crate::utils::version;
1617
17-pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
18+pub fn handle_msg(mut msg: Msg, json: bool) -> anyhow::Result<()> {
19+ // For actions taking paths, prepend the niri CLI's working directory.
20+ if let Msg::Action {
21+ action:
22+ Action::Screenshot { path, .. }
23+ | Action::ScreenshotScreen { path, .. }
24+ | Action::ScreenshotWindow { path, .. },
25+ } = &mut msg
26+ {
27+ if let Some(path) = path {
28+ ensure_absolute_path(path).context("error making the path absolute")?;
29+ }
30+ }
31+
1832 let request = match &msg {
1933 Msg::Version => Request::Version,
2034 Msg::Outputs => Request::Outputs,
@@ -668,6 +682,19 @@ fn fmt_rounded(x: f64) -> String {
668682 }
669683 }
670684
685+fn ensure_absolute_path(path: &mut String) -> anyhow::Result<()> {
686+ let p = Path::new(path);
687+ if p.is_relative() {
688+ let mut cwd = env::current_dir().context("error getting current working directory")?;
689+ cwd.push(p);
690+ match cwd.into_os_string().into_string() {
691+ Ok(absolute) => *path = absolute,
692+ Err(cwd) => bail!("couldn't convert absolute path to string: {cwd:?}"),
693+ }
694+ }
695+ Ok(())
696+}
697+
671698 #[cfg(test)]
672699 mod tests {
673700 use insta::assert_snapshot;
src/ipc/server.rsmodified+22 -3
@@ -2,7 +2,7 @@ use std::cell::RefCell;
22 use std::collections::HashSet;
33 use std::ffi::OsStr;
44 use std::os::unix::net::{UnixListener, UnixStream};
5-use std::path::PathBuf;
5+use std::path::{Path, PathBuf};
66 use std::rc::Rc;
77 use std::sync::{Arc, Mutex};
88 use std::{env, io, process};
@@ -17,8 +17,8 @@ use futures_util::{select_biased, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, Fu
1717 use niri_config::OutputName;
1818 use niri_ipc::state::{EventStreamState, EventStreamStatePart as _};
1919 use niri_ipc::{
20- Event, KeyboardLayouts, OutputConfigChanged, Overview, Reply, Request, Response, WindowLayout,
21- Workspace,
20+ Action, Event, KeyboardLayouts, OutputConfigChanged, Overview, Reply, Request, Response,
21+ WindowLayout, Workspace,
2222 };
2323 use smithay::desktop::layer_map_for_output;
2424 use smithay::input::pointer::{
@@ -379,6 +379,8 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
379379 Response::PickedColor(color)
380380 }
381381 Request::Action(action) => {
382+ validate_action(&action)?;
383+
382384 let (tx, rx) = async_channel::bounded(1);
383385
384386 let action = niri_config::Action::from(action);
@@ -451,6 +453,23 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
451453 Ok(response)
452454 }
453455
456+fn validate_action(action: &Action) -> Result<(), String> {
457+ if let Action::Screenshot { path, .. }
458+ | Action::ScreenshotScreen { path, .. }
459+ | Action::ScreenshotWindow { path, .. } = action
460+ {
461+ if let Some(path) = path {
462+ // Relative paths are resolved against the niri compositor's working directory, which
463+ // is almost certainly not what you want.
464+ if !Path::new(path).is_absolute() {
465+ return Err(format!("path must be absolute: {path}"));
466+ }
467+ }
468+ }
469+
470+ Ok(())
471+}
472+
454473 async fn handle_event_stream_client(client: EventStreamClient) -> anyhow::Result<()> {
455474 let EventStreamClient {
456475 events,
src/niri.rsmodified+32 -18
@@ -1835,7 +1835,7 @@ impl State {
18351835 self.niri.output_management_state.notify_changes(new_config);
18361836 }
18371837
1838- pub fn open_screenshot_ui(&mut self, show_pointer: bool) {
1838+ pub fn open_screenshot_ui(&mut self, show_pointer: bool, path: Option<String>) {
18391839 if self.niri.is_locked() || self.niri.screenshot_ui.is_open() {
18401840 return;
18411841 }
@@ -1876,7 +1876,7 @@ impl State {
18761876 self.backend.with_primary_renderer(|renderer| {
18771877 self.niri
18781878 .screenshot_ui
1879- .open(renderer, screenshots, default_output, show_pointer)
1879+ .open(renderer, screenshots, default_output, show_pointer, path)
18801880 });
18811881
18821882 self.niri
@@ -1902,14 +1902,15 @@ impl State {
19021902 }
19031903
19041904 pub fn confirm_screenshot(&mut self, write_to_disk: bool) {
1905- if !self.niri.screenshot_ui.is_open() {
1905+ let ScreenshotUi::Open { path, .. } = &mut self.niri.screenshot_ui else {
19061906 return;
1907- }
1907+ };
1908+ let path = path.take();
19081909
19091910 self.backend.with_primary_renderer(|renderer| {
19101911 match self.niri.screenshot_ui.capture(renderer) {
19111912 Ok((size, pixels)) => {
1912- if let Err(err) = self.niri.save_screenshot(size, pixels, write_to_disk) {
1913+ if let Err(err) = self.niri.save_screenshot(size, pixels, write_to_disk, path) {
19131914 warn!("error saving screenshot: {err:?}");
19141915 }
19151916 }
@@ -5533,6 +5534,7 @@ impl Niri {
55335534 output: &Output,
55345535 write_to_disk: bool,
55355536 include_pointer: bool,
5537+ path: Option<String>,
55365538 ) -> anyhow::Result<()> {
55375539 let _span = tracy_client::span!("Niri::screenshot");
55385540
@@ -5559,7 +5561,7 @@ impl Niri {
55595561 elements,
55605562 )?;
55615563
5562- self.save_screenshot(size, pixels, write_to_disk)
5564+ self.save_screenshot(size, pixels, write_to_disk, path)
55635565 .context("error saving screenshot")
55645566 }
55655567
@@ -5569,6 +5571,7 @@ impl Niri {
55695571 output: &Output,
55705572 mapped: &Mapped,
55715573 write_to_disk: bool,
5574+ path: Option<String>,
55725575 ) -> anyhow::Result<()> {
55735576 let _span = tracy_client::span!("Niri::screenshot_window");
55745577
@@ -5600,7 +5603,7 @@ impl Niri {
56005603 elements,
56015604 )?;
56025605
5603- self.save_screenshot(geo.size, pixels, write_to_disk)
5606+ self.save_screenshot(geo.size, pixels, write_to_disk, path)
56045607 .context("error saving screenshot")
56055608 }
56065609
@@ -5609,14 +5612,20 @@ impl Niri {
56095612 size: Size<i32, Physical>,
56105613 pixels: Vec<u8>,
56115614 write_to_disk: bool,
5615+ path_arg: Option<String>,
56125616 ) -> anyhow::Result<()> {
56135617 let path = write_to_disk
5614- .then(|| match make_screenshot_path(&self.config.borrow()) {
5615- Ok(path) => path,
5616- Err(err) => {
5617- warn!("error making screenshot path: {err:?}");
5618- None
5619- }
5618+ .then(|| {
5619+ // When given an explicit path, don't try to strftime it or create parents.
5620+ path_arg.map(|p| (PathBuf::from(p), false)).or_else(|| {
5621+ match make_screenshot_path(&self.config.borrow()) {
5622+ Ok(path) => path.map(|p| (p, true)),
5623+ Err(err) => {
5624+ warn!("error making screenshot path: {err:?}");
5625+ None
5626+ }
5627+ }
5628+ })
56205629 })
56215630 .flatten();
56225631
@@ -5652,13 +5661,18 @@ impl Niri {
56525661
56535662 let mut image_path = None;
56545663
5655- if let Some(path) = path {
5664+ if let Some((path, create_parent)) = path {
56565665 debug!("saving screenshot to {path:?}");
56575666
5658- if let Some(parent) = path.parent() {
5659- if let Err(err) = std::fs::create_dir(parent) {
5660- if err.kind() != std::io::ErrorKind::AlreadyExists {
5661- warn!("error creating screenshot directory: {err:?}");
5667+ if create_parent {
5668+ if let Some(parent) = path.parent() {
5669+ // Relative paths with one component, i.e. "test.png", have Some("") parent.
5670+ if !parent.as_os_str().is_empty() {
5671+ if let Err(err) = std::fs::create_dir(parent) {
5672+ if err.kind() != std::io::ErrorKind::AlreadyExists {
5673+ warn!("error creating screenshot directory: {err:?}");
5674+ }
5675+ }
56625676 }
56635677 }
56645678 }
src/ui/hotkey_overlay.rsmodified+10 -10
@@ -263,7 +263,7 @@ fn collect_actions(config: &Config) -> Vec<&Action> {
263263 // Screenshot is not as important, can omit if not bound.
264264 if let Some(bind) = binds
265265 .iter()
266- .find(|bind| matches!(bind.action, Action::Screenshot(_)))
266+ .find(|bind| matches!(bind.action, Action::Screenshot(_, _)))
267267 {
268268 actions.push(&bind.action);
269269 }
@@ -479,7 +479,7 @@ fn action_name(action: &Action) -> String {
479479 String::from("Switch Focus Between Floating and Tiling")
480480 }
481481 Action::ToggleOverview => String::from("Open the Overview"),
482- Action::Screenshot(_) => String::from("Take a Screenshot"),
482+ Action::Screenshot(_, _) => String::from("Take a Screenshot"),
483483 Action::Spawn(args) => format!(
484484 "Spawn <span face='monospace' bgcolor='#000000'>{}</span>",
485485 args.first().unwrap_or(&String::new())
@@ -620,7 +620,7 @@ mod tests {
620620 #[test]
621621 fn test_format_bind() {
622622 // Not bound.
623- assert_snapshot!(check("", Action::Screenshot(true)), @" (not bound) : Take a Screenshot");
623+ assert_snapshot!(check("", Action::Screenshot(true, None)), @" (not bound) : Take a Screenshot");
624624
625625 // Bound with a default title.
626626 assert_snapshot!(
@@ -628,7 +628,7 @@ mod tests {
628628 r#"binds {
629629 Mod+P { screenshot; }
630630 }"#,
631- Action::Screenshot(true),
631+ Action::Screenshot(true, None),
632632 ),
633633 @" Super + P : Take a Screenshot"
634634 );
@@ -639,7 +639,7 @@ mod tests {
639639 r#"binds {
640640 Mod+P hotkey-overlay-title="Hello" { screenshot; }
641641 }"#,
642- Action::Screenshot(true),
642+ Action::Screenshot(true, None),
643643 ),
644644 @" Super + P : Hello"
645645 );
@@ -651,7 +651,7 @@ mod tests {
651651 Mod+P { screenshot; }
652652 Print { screenshot; }
653653 }"#,
654- Action::Screenshot(true),
654+ Action::Screenshot(true, None),
655655 ),
656656 @" Super + P : Take a Screenshot"
657657 );
@@ -663,7 +663,7 @@ mod tests {
663663 Mod+P { screenshot; }
664664 Print hotkey-overlay-title="My Cool Bind" { screenshot; }
665665 }"#,
666- Action::Screenshot(true),
666+ Action::Screenshot(true, None),
667667 ),
668668 @" PrtSc : My Cool Bind"
669669 );
@@ -675,7 +675,7 @@ mod tests {
675675 Mod+P hotkey-overlay-title="First" { screenshot; }
676676 Print hotkey-overlay-title="My Cool Bind" { screenshot; }
677677 }"#,
678- Action::Screenshot(true),
678+ Action::Screenshot(true, None),
679679 ),
680680 @" Super + P : First"
681681 );
@@ -687,7 +687,7 @@ mod tests {
687687 Mod+P { screenshot; }
688688 Print hotkey-overlay-title=null { screenshot; }
689689 }"#,
690- Action::Screenshot(true),
690+ Action::Screenshot(true, None),
691691 ),
692692 @"None"
693693 );
@@ -699,7 +699,7 @@ mod tests {
699699 Mod+P hotkey-overlay-title="Hello" { screenshot; }
700700 Print hotkey-overlay-title=null { screenshot; }
701701 }"#,
702- Action::Screenshot(true),
702+ Action::Screenshot(true, None),
703703 ),
704704 @" Super + P : Hello"
705705 );
src/ui/screenshot_ui.rsmodified+3 -0
@@ -63,6 +63,7 @@ pub enum ScreenshotUi {
6363 open_anim: Animation,
6464 clock: Clock,
6565 config: Rc<RefCell<Config>>,
66+ path: Option<String>,
6667 },
6768 }
6869
@@ -141,6 +142,7 @@ impl ScreenshotUi {
141142 screenshots: HashMap<Output, [OutputScreenshot; 3]>,
142143 default_output: Output,
143144 show_pointer: bool,
145+ path: Option<String>,
144146 ) -> bool {
145147 if screenshots.is_empty() {
146148 return false;
@@ -235,6 +237,7 @@ impl ScreenshotUi {
235237 open_anim,
236238 clock: clock.clone(),
237239 config: config.clone(),
240+ path,
238241 };
239242
240243 self.update_buffers();