forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBf2ce84bYuya Nishihara2 years ago1130 commits

mod.rs224 lines, 7.1 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 bitflags::bitflags;
11use directories::UserDirs;
12use git_version::git_version;
13use niri_config::Config;
14use smithay::input::pointer::CursorIcon;
15use smithay::output::Output;
16use smithay::reexports::rustix::time::{clock_gettime, ClockId};
17use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
18use smithay::utils::{Logical, Point, Rectangle, Size, Transform};
19
20pub mod id;
21pub mod scale;
22pub mod spawning;
23pub mod watcher;
24
25pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
26
27bitflags! {
28 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29 pub struct ResizeEdge: u32 {
30 const TOP = 0b0001;
31 const BOTTOM = 0b0010;
32 const LEFT = 0b0100;
33 const RIGHT = 0b1000;
34
35 const TOP_LEFT = Self::TOP.bits() | Self::LEFT.bits();
36 const BOTTOM_LEFT = Self::BOTTOM.bits() | Self::LEFT.bits();
37
38 const TOP_RIGHT = Self::TOP.bits() | Self::RIGHT.bits();
39 const BOTTOM_RIGHT = Self::BOTTOM.bits() | Self::RIGHT.bits();
40
41 const LEFT_RIGHT = Self::LEFT.bits() | Self::RIGHT.bits();
42 const TOP_BOTTOM = Self::TOP.bits() | Self::BOTTOM.bits();
43 }
44}
45
46impl From<xdg_toplevel::ResizeEdge> for ResizeEdge {
47 #[inline]
48 fn from(x: xdg_toplevel::ResizeEdge) -> Self {
49 Self::from_bits(x as u32).unwrap()
50 }
51}
52
53impl ResizeEdge {
54 pub fn cursor_icon(self) -> CursorIcon {
55 match self {
56 Self::LEFT => CursorIcon::WResize,
57 Self::RIGHT => CursorIcon::EResize,
58 Self::TOP => CursorIcon::NResize,
59 Self::BOTTOM => CursorIcon::SResize,
60 Self::TOP_LEFT => CursorIcon::NwResize,
61 Self::TOP_RIGHT => CursorIcon::NeResize,
62 Self::BOTTOM_RIGHT => CursorIcon::SeResize,
63 Self::BOTTOM_LEFT => CursorIcon::SwResize,
64 _ => CursorIcon::Default,
65 }
66 }
67}
68
69pub fn version() -> String {
70 format!(
71 "{} ({})",
72 env!("CARGO_PKG_VERSION"),
73 git_version!(fallback = "unknown commit"),
74 )
75}
76
77pub fn get_monotonic_time() -> Duration {
78 let ts = clock_gettime(ClockId::Monotonic);
79 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
80}
81
82pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
83 rect.loc + rect.size.downscale(2).to_point()
84}
85
86pub fn center_f64(rect: Rectangle<f64, Logical>) -> Point<f64, Logical> {
87 rect.loc + rect.size.downscale(2.0).to_point()
88}
89
90pub fn output_size(output: &Output) -> Size<i32, Logical> {
91 let output_scale = output.current_scale().integer_scale();
92 let output_transform = output.current_transform();
93 let output_mode = output.current_mode().unwrap();
94
95 output_transform
96 .transform_size(output_mode.size)
97 .to_logical(output_scale)
98}
99
100pub fn logical_output(output: &Output) -> niri_ipc::LogicalOutput {
101 let loc = output.current_location();
102 let size = output_size(output);
103 let transform = match output.current_transform() {
104 Transform::Normal => niri_ipc::Transform::Normal,
105 Transform::_90 => niri_ipc::Transform::_90,
106 Transform::_180 => niri_ipc::Transform::_180,
107 Transform::_270 => niri_ipc::Transform::_270,
108 Transform::Flipped => niri_ipc::Transform::Flipped,
109 Transform::Flipped90 => niri_ipc::Transform::Flipped90,
110 Transform::Flipped180 => niri_ipc::Transform::Flipped180,
111 Transform::Flipped270 => niri_ipc::Transform::Flipped270,
112 };
113 niri_ipc::LogicalOutput {
114 x: loc.x,
115 y: loc.y,
116 width: size.w as u32,
117 height: size.h as u32,
118 scale: output.current_scale().fractional_scale(),
119 transform,
120 }
121}
122
123pub fn ipc_transform_to_smithay(transform: niri_ipc::Transform) -> Transform {
124 match transform {
125 niri_ipc::Transform::Normal => Transform::Normal,
126 niri_ipc::Transform::_90 => Transform::_90,
127 niri_ipc::Transform::_180 => Transform::_180,
128 niri_ipc::Transform::_270 => Transform::_270,
129 niri_ipc::Transform::Flipped => Transform::Flipped,
130 niri_ipc::Transform::Flipped90 => Transform::Flipped90,
131 niri_ipc::Transform::Flipped180 => Transform::Flipped180,
132 niri_ipc::Transform::Flipped270 => Transform::Flipped270,
133 }
134}
135
136pub fn expand_home(path: &Path) -> anyhow::Result<Option<PathBuf>> {
137 if let Ok(rest) = path.strip_prefix("~") {
138 let dirs = UserDirs::new().context("error retrieving home directory")?;
139 Ok(Some([dirs.home_dir(), rest].iter().collect()))
140 } else {
141 Ok(None)
142 }
143}
144
145pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> {
146 let Some(path) = &config.screenshot_path else {
147 return Ok(None);
148 };
149
150 let format = CString::new(path.clone()).context("path must not contain nul bytes")?;
151
152 let mut buf = [0u8; 2048];
153 let mut path;
154 unsafe {
155 let time = libc::time(null_mut());
156 ensure!(time != -1, "error in time()");
157
158 let tm = libc::localtime(&time);
159 ensure!(!tm.is_null(), "error in localtime()");
160
161 let rv = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), format.as_ptr(), tm);
162 ensure!(rv != 0, "error formatting time");
163
164 path = PathBuf::from(OsStr::from_bytes(&buf[..rv]));
165 }
166
167 if let Some(expanded) = expand_home(&path).context("error expanding ~")? {
168 path = expanded;
169 }
170
171 Ok(Some(path))
172}
173
174pub fn write_png_rgba8(
175 w: impl Write,
176 width: u32,
177 height: u32,
178 pixels: &[u8],
179) -> Result<(), png::EncodingError> {
180 let mut encoder = png::Encoder::new(w, width, height);
181 encoder.set_color(png::ColorType::Rgba);
182 encoder.set_depth(png::BitDepth::Eight);
183
184 let mut writer = encoder.write_header()?;
185 writer.write_image_data(pixels)
186}
187
188#[cfg(feature = "dbus")]
189pub fn show_screenshot_notification(image_path: Option<PathBuf>) {
190 let mut notification = notify_rust::Notification::new();
191 notification
192 .summary("Screenshot captured")
193 .body("You can paste the image from the clipboard.")
194 .urgency(notify_rust::Urgency::Normal)
195 .hint(notify_rust::Hint::Transient(true));
196
197 // Try to add the screenshot as an image if possible.
198 if let Some(path) = image_path {
199 match path.canonicalize() {
200 Ok(path) => match url::Url::from_file_path(path) {
201 Ok(url) => {
202 notification.image_path(url.as_str());
203 }
204 Err(err) => {
205 warn!("error converting screenshot path to file url: {err:?}");
206 }
207 },
208 Err(err) => {
209 warn!("error canonicalizing screenshot path: {err:?}");
210 }
211 }
212 }
213
214 if let Err(err) = notification.show() {
215 warn!("error showing screenshot notification: {err:?}");
216 }
217}
218
219#[inline(never)]
220pub fn cause_panic() {
221 let a = Duration::from_secs(1);
222 let b = Duration::from_secs(2);
223 let _ = a - b;
224}