forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBe1971c4Ivan Molodetskikh2 years ago493 commits

utils.rs192 lines, 5.7 KiBHistoryRawDownload
1use std::ffi::{CString, OsStr};
2use std::io::{self, Write};
3use std::os::unix::prelude::OsStrExt;
4use std::os::unix::process::CommandExt;
5use std::path::PathBuf;
6use std::process::{Command, Stdio};
7use std::ptr::null_mut;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::thread;
10use std::time::Duration;
11
12use anyhow::{ensure, Context};
13use directories::UserDirs;
14use niri_config::Config;
15use smithay::output::Output;
16use smithay::reexports::rustix::time::{clock_gettime, ClockId};
17use smithay::utils::{Logical, Point, Rectangle, Size};
18
19pub fn clone2<T: Clone, U: Clone>(t: (&T, &U)) -> (T, U) {
20 (t.0.clone(), t.1.clone())
21}
22
23pub fn get_monotonic_time() -> Duration {
24 let ts = clock_gettime(ClockId::Monotonic);
25 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
26}
27
28pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
29 rect.loc + rect.size.downscale(2).to_point()
30}
31
32pub fn output_size(output: &Output) -> Size<i32, Logical> {
33 let output_scale = output.current_scale().integer_scale();
34 let output_transform = output.current_transform();
35 let output_mode = output.current_mode().unwrap();
36
37 output_transform
38 .transform_size(output_mode.size)
39 .to_logical(output_scale)
40}
41
42pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> {
43 let Some(path) = &config.screenshot_path else {
44 return Ok(None);
45 };
46
47 let format = CString::new(path.clone()).context("path must not contain nul bytes")?;
48
49 let mut buf = [0u8; 2048];
50 let mut path;
51 unsafe {
52 let time = libc::time(null_mut());
53 ensure!(time != -1, "error in time()");
54
55 let tm = libc::localtime(&time);
56 ensure!(!tm.is_null(), "error in localtime()");
57
58 let rv = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), format.as_ptr(), tm);
59 ensure!(rv != 0, "error formatting time");
60
61 path = PathBuf::from(OsStr::from_bytes(&buf[..rv]));
62 }
63
64 if let Ok(rest) = path.strip_prefix("~") {
65 let dirs = UserDirs::new().context("error retrieving home directory")?;
66 path = [dirs.home_dir(), rest].iter().collect();
67 }
68
69 Ok(Some(path))
70}
71
72pub static REMOVE_ENV_RUST_BACKTRACE: AtomicBool = AtomicBool::new(false);
73pub static REMOVE_ENV_RUST_LIB_BACKTRACE: AtomicBool = AtomicBool::new(false);
74
75/// Spawns the command to run independently of the compositor.
76pub fn spawn<T: AsRef<OsStr> + Send + 'static>(command: Vec<T>) {
77 let _span = tracy_client::span!();
78
79 if command.is_empty() {
80 return;
81 }
82
83 // Spawning and waiting takes some milliseconds, so do it in a thread.
84 let res = thread::Builder::new()
85 .name("Command Spawner".to_owned())
86 .spawn(move || {
87 let (command, args) = command.split_first().unwrap();
88 spawn_sync(command, args);
89 });
90
91 if let Err(err) = res {
92 warn!("error spawning a thread to spawn the command: {err:?}");
93 }
94}
95
96fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl AsRef<OsStr>>) {
97 let _span = tracy_client::span!();
98
99 let command = command.as_ref();
100
101 let mut process = Command::new(command);
102 process
103 .args(args)
104 .stdin(Stdio::null())
105 .stdout(Stdio::null())
106 .stderr(Stdio::null());
107
108 // Remove RUST_BACKTRACE and RUST_LIB_BACKTRACE from the environment if needed.
109 if REMOVE_ENV_RUST_BACKTRACE.load(Ordering::Relaxed) {
110 process.env_remove("RUST_BACKTRACE");
111 }
112 if REMOVE_ENV_RUST_LIB_BACKTRACE.load(Ordering::Relaxed) {
113 process.env_remove("RUST_LIB_BACKTRACE");
114 }
115
116 // Double-fork to avoid having to waitpid the child.
117 unsafe {
118 process.pre_exec(|| {
119 match libc::fork() {
120 -1 => return Err(io::Error::last_os_error()),
121 0 => (),
122 _ => libc::_exit(0),
123 }
124
125 Ok(())
126 });
127 }
128
129 let mut child = match process.spawn() {
130 Ok(child) => child,
131 Err(err) => {
132 warn!("error spawning {command:?}: {err:?}");
133 return;
134 }
135 };
136
137 match child.wait() {
138 Ok(status) => {
139 if !status.success() {
140 warn!("child did not exit successfully: {status:?}");
141 }
142 }
143 Err(err) => {
144 warn!("error waiting for child: {err:?}");
145 }
146 }
147}
148
149pub fn write_png_rgba8(
150 w: impl Write,
151 width: u32,
152 height: u32,
153 pixels: &[u8],
154) -> Result<(), png::EncodingError> {
155 let mut encoder = png::Encoder::new(w, width, height);
156 encoder.set_color(png::ColorType::Rgba);
157 encoder.set_depth(png::BitDepth::Eight);
158
159 let mut writer = encoder.write_header()?;
160 writer.write_image_data(pixels)
161}
162
163#[cfg(feature = "dbus")]
164pub fn show_screenshot_notification(image_path: Option<PathBuf>) {
165 let mut notification = notify_rust::Notification::new();
166 notification
167 .summary("Screenshot captured")
168 .body("You can paste the image from the clipboard.")
169 .urgency(notify_rust::Urgency::Normal)
170 .hint(notify_rust::Hint::Transient(true));
171
172 // Try to add the screenshot as an image if possible.
173 if let Some(path) = image_path {
174 match path.canonicalize() {
175 Ok(path) => match url::Url::from_file_path(path) {
176 Ok(url) => {
177 notification.image_path(url.as_str());
178 }
179 Err(err) => {
180 warn!("error converting screenshot path to file url: {err:?}");
181 }
182 },
183 Err(err) => {
184 warn!("error canonicalizing screenshot path: {err:?}");
185 }
186 }
187 }
188
189 if let Err(err) = notification.show() {
190 warn!("error showing screenshot notification: {err:?}");
191 }
192}