forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBe0ec6e5Ivan Molodetskikh2 years ago752 commits

mod.rs141 lines, 4.0 KiBHistoryRawDownload
1use std::ffi::{CString, OsStr};
2use std::io::Write;
3use std::os::unix::prelude::OsStrExt;
4use std::path::{Path, PathBuf};
5use std::ptr::null_mut;
6use std::sync::atomic::AtomicBool;
7use std::time::Duration;
8
9use anyhow::{ensure, Context};
10use directories::UserDirs;
11use git_version::git_version;
12use niri_config::Config;
13use smithay::output::Output;
14use smithay::reexports::rustix::time::{clock_gettime, ClockId};
15use smithay::utils::{Logical, Point, Rectangle, Size};
16
17pub mod spawning;
18pub mod watcher;
19
20pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
21
22pub fn clone2<T: Clone, U: Clone>(t: (&T, &U)) -> (T, U) {
23 (t.0.clone(), t.1.clone())
24}
25
26pub fn version() -> String {
27 format!(
28 "{} ({})",
29 env!("CARGO_PKG_VERSION"),
30 git_version!(fallback = "unknown commit"),
31 )
32}
33
34pub fn get_monotonic_time() -> Duration {
35 let ts = clock_gettime(ClockId::Monotonic);
36 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
37}
38
39pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
40 rect.loc + rect.size.downscale(2).to_point()
41}
42
43pub fn output_size(output: &Output) -> Size<i32, Logical> {
44 let output_scale = output.current_scale().integer_scale();
45 let output_transform = output.current_transform();
46 let output_mode = output.current_mode().unwrap();
47
48 output_transform
49 .transform_size(output_mode.size)
50 .to_logical(output_scale)
51}
52
53pub fn expand_home(path: &Path) -> anyhow::Result<Option<PathBuf>> {
54 if let Ok(rest) = path.strip_prefix("~") {
55 let dirs = UserDirs::new().context("error retrieving home directory")?;
56 Ok(Some([dirs.home_dir(), rest].iter().collect()))
57 } else {
58 Ok(None)
59 }
60}
61
62pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> {
63 let Some(path) = &config.screenshot_path else {
64 return Ok(None);
65 };
66
67 let format = CString::new(path.clone()).context("path must not contain nul bytes")?;
68
69 let mut buf = [0u8; 2048];
70 let mut path;
71 unsafe {
72 let time = libc::time(null_mut());
73 ensure!(time != -1, "error in time()");
74
75 let tm = libc::localtime(&time);
76 ensure!(!tm.is_null(), "error in localtime()");
77
78 let rv = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), format.as_ptr(), tm);
79 ensure!(rv != 0, "error formatting time");
80
81 path = PathBuf::from(OsStr::from_bytes(&buf[..rv]));
82 }
83
84 if let Some(expanded) = expand_home(&path).context("error expanding ~")? {
85 path = expanded;
86 }
87
88 Ok(Some(path))
89}
90
91pub fn write_png_rgba8(
92 w: impl Write,
93 width: u32,
94 height: u32,
95 pixels: &[u8],
96) -> Result<(), png::EncodingError> {
97 let mut encoder = png::Encoder::new(w, width, height);
98 encoder.set_color(png::ColorType::Rgba);
99 encoder.set_depth(png::BitDepth::Eight);
100
101 let mut writer = encoder.write_header()?;
102 writer.write_image_data(pixels)
103}
104
105#[cfg(feature = "dbus")]
106pub fn show_screenshot_notification(image_path: Option<PathBuf>) {
107 let mut notification = notify_rust::Notification::new();
108 notification
109 .summary("Screenshot captured")
110 .body("You can paste the image from the clipboard.")
111 .urgency(notify_rust::Urgency::Normal)
112 .hint(notify_rust::Hint::Transient(true));
113
114 // Try to add the screenshot as an image if possible.
115 if let Some(path) = image_path {
116 match path.canonicalize() {
117 Ok(path) => match url::Url::from_file_path(path) {
118 Ok(url) => {
119 notification.image_path(url.as_str());
120 }
121 Err(err) => {
122 warn!("error converting screenshot path to file url: {err:?}");
123 }
124 },
125 Err(err) => {
126 warn!("error canonicalizing screenshot path: {err:?}");
127 }
128 }
129 }
130
131 if let Err(err) = notification.show() {
132 warn!("error showing screenshot notification: {err:?}");
133 }
134}
135
136#[inline(never)]
137pub fn cause_panic() {
138 let a = Duration::from_secs(1);
139 let b = Duration::from_secs(2);
140 let _ = a - b;
141}