| 1 | use std::ffi::{CString, OsStr}; |
| 2 | use std::io::{self, Write}; |
| 3 | use std::os::unix::prelude::OsStrExt; |
| 4 | use std::os::unix::process::CommandExt; |
| 5 | use std::path::PathBuf; |
| 6 | use std::process::{Command, Stdio}; |
| 7 | use std::ptr::null_mut; |
| 8 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 9 | use std::thread; |
| 10 | use std::time::Duration; |
| 11 | |
| 12 | use anyhow::{ensure, Context}; |
| 13 | use directories::UserDirs; |
| 14 | use git_version::git_version; |
| 15 | use niri_config::Config; |
| 16 | use smithay::output::Output; |
| 17 | use smithay::reexports::rustix::time::{clock_gettime, ClockId}; |
| 18 | use smithay::utils::{Logical, Point, Rectangle, Size}; |
| 19 | |
| 20 | pub fn clone2<T: Clone, U: Clone>(t: (&T, &U)) -> (T, U) { |
| 21 | (t.0.clone(), t.1.clone()) |
| 22 | } |
| 23 | |
| 24 | pub fn version() -> String { |
| 25 | format!( |
| 26 | "{} ({})", |
| 27 | env!("CARGO_PKG_VERSION"), |
| 28 | git_version!(fallback = "unknown commit"), |
| 29 | ) |
| 30 | } |
| 31 | |
| 32 | pub 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 | |
| 37 | pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> { |
| 38 | rect.loc + rect.size.downscale(2).to_point() |
| 39 | } |
| 40 | |
| 41 | pub 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 | |
| 51 | pub 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 | |
| 81 | pub static REMOVE_ENV_RUST_BACKTRACE: AtomicBool = AtomicBool::new(false); |
| 82 | pub static REMOVE_ENV_RUST_LIB_BACKTRACE: AtomicBool = AtomicBool::new(false); |
| 83 | |
| 84 | |
| 85 | pub 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 | |
| 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 | |
| 105 | fn 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 | |
| 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 | |
| 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 | |
| 158 | pub 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")] |
| 173 | pub 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 | |
| 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)] |
| 204 | pub fn cause_panic() { |
| 205 | let a = Duration::from_secs(1); |
| 206 | let b = Duration::from_secs(2); |
| 207 | let _ = a - b; |
| 208 | } |