forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBbe6e25fIvan Molodetskikh2 years ago468 commits

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