| 1 | use std::ffi::OsStr; |
| 2 | use std::io; |
| 3 | use std::os::unix::process::CommandExt; |
| 4 | use std::path::PathBuf; |
| 5 | use std::process::{Command, Stdio}; |
| 6 | use std::time::Duration; |
| 7 | |
| 8 | use anyhow::Context; |
| 9 | use directories::UserDirs; |
| 10 | use nix::time::{clock_gettime, ClockId}; |
| 11 | use smithay::utils::{Logical, Point, Rectangle}; |
| 12 | use time::OffsetDateTime; |
| 13 | |
| 14 | pub fn get_monotonic_time() -> Duration { |
| 15 | Duration::from(clock_gettime(ClockId::CLOCK_MONOTONIC).unwrap()) |
| 16 | } |
| 17 | |
| 18 | pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> { |
| 19 | rect.loc + rect.size.downscale(2).to_point() |
| 20 | } |
| 21 | |
| 22 | pub fn make_screenshot_path() -> anyhow::Result<PathBuf> { |
| 23 | let dirs = UserDirs::new().context("error retrieving home directory")?; |
| 24 | let mut path = dirs.picture_dir().map(|p| p.to_owned()).unwrap_or_else(|| { |
| 25 | let mut dir = dirs.home_dir().to_owned(); |
| 26 | dir.push("Pictures"); |
| 27 | dir |
| 28 | }); |
| 29 | path.push("Screenshots"); |
| 30 | |
| 31 | unsafe { |
| 32 | |
| 33 | time::util::local_offset::set_soundness(time::util::local_offset::Soundness::Unsound); |
| 34 | }; |
| 35 | |
| 36 | let now = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()); |
| 37 | let desc = time::macros::format_description!( |
| 38 | "Screenshot from [year]-[month]-[day] [hour]-[minute]-[second].png" |
| 39 | ); |
| 40 | let name = now.format(desc).context("error formatting time")?; |
| 41 | path.push(name); |
| 42 | |
| 43 | Ok(path) |
| 44 | } |
| 45 | |
| 46 | |
| 47 | pub fn spawn(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl AsRef<OsStr>>) { |
| 48 | let _span = tracy_client::span!(); |
| 49 | |
| 50 | let command = command.as_ref(); |
| 51 | |
| 52 | let mut process = Command::new(command); |
| 53 | process |
| 54 | .args(args) |
| 55 | .stdin(Stdio::null()) |
| 56 | .stdout(Stdio::null()) |
| 57 | .stderr(Stdio::null()); |
| 58 | |
| 59 | |
| 60 | unsafe { |
| 61 | process.pre_exec(|| { |
| 62 | match libc::fork() { |
| 63 | -1 => return Err(io::Error::last_os_error()), |
| 64 | 0 => (), |
| 65 | _ => libc::_exit(0), |
| 66 | } |
| 67 | |
| 68 | Ok(()) |
| 69 | }); |
| 70 | } |
| 71 | |
| 72 | let mut child = match process.spawn() { |
| 73 | Ok(child) => child, |
| 74 | Err(err) => { |
| 75 | warn!("error spawning {command:?}: {err:?}"); |
| 76 | return; |
| 77 | } |
| 78 | }; |
| 79 | |
| 80 | match child.wait() { |
| 81 | Ok(status) => { |
| 82 | if !status.success() { |
| 83 | warn!("child did not exit successfully: {status:?}"); |
| 84 | } |
| 85 | } |
| 86 | Err(err) => { |
| 87 | warn!("error waiting for child: {err:?}"); |
| 88 | } |
| 89 | } |
| 90 | } |