forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBbefdebfIvan Molodetskikh2 years ago681 commits

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