forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB0411fd8Ivan Molodetskikh3 years ago263 commits

utils.rs90 lines, 2.5 KiBHistoryRawDownload
1use std::ffi::OsStr;
2use std::io;
3use std::os::unix::process::CommandExt;
4use std::path::PathBuf;
5use std::process::{Command, Stdio};
6use std::time::Duration;
7
8use anyhow::Context;
9use directories::UserDirs;
10use nix::time::{clock_gettime, ClockId};
11use smithay::utils::{Logical, Point, Rectangle};
12use time::OffsetDateTime;
13
14pub fn get_monotonic_time() -> Duration {
15 Duration::from(clock_gettime(ClockId::CLOCK_MONOTONIC).unwrap())
16}
17
18pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
19 rect.loc + rect.size.downscale(2).to_point()
20}
21
22pub 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 // are you kidding me
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/// Spawns the command to run independently of the compositor.
47pub 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 // Double-fork to avoid having to waitpid the child.
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}