forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB7b3bef1Suyashtnt2 years ago1225 commits

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