forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBdde9214Ivan Molodetskikh1 year ago1835 commits

mod.rs421 lines, 13.0 KiBHistoryRawDownload
1use std::cmp::{max, min};
2use std::ffi::{CString, OsStr};
3use std::io::Write;
4use std::os::unix::prelude::OsStrExt;
5use std::path::{Path, PathBuf};
6use std::ptr::null_mut;
7use std::sync::atomic::AtomicBool;
8use std::time::Duration;
9
10use anyhow::{ensure, Context};
11use bitflags::bitflags;
12use directories::UserDirs;
13use git_version::git_version;
14use niri_config::{Config, OutputName};
15use smithay::input::pointer::CursorIcon;
16use smithay::output::{self, Output};
17use smithay::reexports::rustix::time::{clock_gettime, ClockId};
18use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
19use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
20use smithay::reexports::wayland_server::{DisplayHandle, Resource as _};
21use smithay::utils::{Coordinate, Logical, Point, Rectangle, Size, Transform};
22use smithay::wayland::compositor::{send_surface_state, with_states, SurfaceData};
23use smithay::wayland::fractional_scale::with_fractional_scale;
24use smithay::wayland::shell::xdg::{
25 ToplevelSurface, XdgToplevelSurfaceData, XdgToplevelSurfaceRoleAttributes,
26};
27use wayland_backend::server::Credentials;
28
29use crate::niri::ClientState;
30
31pub mod id;
32pub mod scale;
33pub mod spawning;
34pub mod transaction;
35pub mod watcher;
36
37pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
38
39bitflags! {
40 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41 pub struct ResizeEdge: u32 {
42 const TOP = 0b0001;
43 const BOTTOM = 0b0010;
44 const LEFT = 0b0100;
45 const RIGHT = 0b1000;
46
47 const TOP_LEFT = Self::TOP.bits() | Self::LEFT.bits();
48 const BOTTOM_LEFT = Self::BOTTOM.bits() | Self::LEFT.bits();
49
50 const TOP_RIGHT = Self::TOP.bits() | Self::RIGHT.bits();
51 const BOTTOM_RIGHT = Self::BOTTOM.bits() | Self::RIGHT.bits();
52
53 const LEFT_RIGHT = Self::LEFT.bits() | Self::RIGHT.bits();
54 const TOP_BOTTOM = Self::TOP.bits() | Self::BOTTOM.bits();
55 }
56}
57
58impl From<xdg_toplevel::ResizeEdge> for ResizeEdge {
59 #[inline]
60 fn from(x: xdg_toplevel::ResizeEdge) -> Self {
61 Self::from_bits(x as u32).unwrap()
62 }
63}
64
65impl ResizeEdge {
66 pub fn cursor_icon(self) -> CursorIcon {
67 match self {
68 Self::LEFT => CursorIcon::WResize,
69 Self::RIGHT => CursorIcon::EResize,
70 Self::TOP => CursorIcon::NResize,
71 Self::BOTTOM => CursorIcon::SResize,
72 Self::TOP_LEFT => CursorIcon::NwResize,
73 Self::TOP_RIGHT => CursorIcon::NeResize,
74 Self::BOTTOM_RIGHT => CursorIcon::SeResize,
75 Self::BOTTOM_LEFT => CursorIcon::SwResize,
76 _ => CursorIcon::Default,
77 }
78 }
79}
80
81pub fn version() -> String {
82 if let Some(v) = option_env!("NIRI_BUILD_VERSION_STRING") {
83 return String::from(v);
84 }
85
86 const MAJOR: &str = env!("CARGO_PKG_VERSION_MAJOR");
87 const MINOR: &str = env!("CARGO_PKG_VERSION_MINOR");
88 const PATCH: &str = env!("CARGO_PKG_VERSION_PATCH");
89
90 let commit =
91 option_env!("NIRI_BUILD_COMMIT").unwrap_or(git_version!(fallback = "unknown commit"));
92
93 if PATCH == "0" {
94 format!("{MAJOR}.{MINOR:0>2} ({commit})")
95 } else {
96 format!("{MAJOR}.{MINOR:0>2}.{PATCH} ({commit})")
97 }
98}
99
100pub fn get_monotonic_time() -> Duration {
101 let ts = clock_gettime(ClockId::Monotonic);
102 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
103}
104
105pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
106 rect.loc + rect.size.downscale(2).to_point()
107}
108
109pub fn center_f64(rect: Rectangle<f64, Logical>) -> Point<f64, Logical> {
110 rect.loc + rect.size.downscale(2.0).to_point()
111}
112
113/// Convert logical pixels to physical, rounding to physical pixels.
114pub fn to_physical_precise_round<N: Coordinate>(scale: f64, logical: impl Coordinate) -> N {
115 N::from_f64((logical.to_f64() * scale).round())
116}
117
118pub fn round_logical_in_physical(scale: f64, logical: f64) -> f64 {
119 (logical * scale).round() / scale
120}
121
122pub fn round_logical_in_physical_max1(scale: f64, logical: f64) -> f64 {
123 if logical == 0. {
124 return 0.;
125 }
126
127 (logical * scale).max(1.).round() / scale
128}
129
130pub fn floor_logical_in_physical_max1(scale: f64, logical: f64) -> f64 {
131 if logical == 0. {
132 return 0.;
133 }
134
135 (logical * scale).max(1.).floor() / scale
136}
137
138pub fn output_size(output: &Output) -> Size<f64, Logical> {
139 let output_scale = output.current_scale().fractional_scale();
140 let output_transform = output.current_transform();
141 let output_mode = output.current_mode().unwrap();
142 let logical_size = output_mode.size.to_f64().to_logical(output_scale);
143 output_transform.transform_size(logical_size)
144}
145
146pub fn logical_output(output: &Output) -> niri_ipc::LogicalOutput {
147 let loc = output.current_location();
148 let size = output_size(output);
149 let transform = match output.current_transform() {
150 Transform::Normal => niri_ipc::Transform::Normal,
151 Transform::_90 => niri_ipc::Transform::_90,
152 Transform::_180 => niri_ipc::Transform::_180,
153 Transform::_270 => niri_ipc::Transform::_270,
154 Transform::Flipped => niri_ipc::Transform::Flipped,
155 Transform::Flipped90 => niri_ipc::Transform::Flipped90,
156 Transform::Flipped180 => niri_ipc::Transform::Flipped180,
157 Transform::Flipped270 => niri_ipc::Transform::Flipped270,
158 };
159 niri_ipc::LogicalOutput {
160 x: loc.x,
161 y: loc.y,
162 width: size.w as u32,
163 height: size.h as u32,
164 scale: output.current_scale().fractional_scale(),
165 transform,
166 }
167}
168
169pub fn ipc_transform_to_smithay(transform: niri_ipc::Transform) -> Transform {
170 match transform {
171 niri_ipc::Transform::Normal => Transform::Normal,
172 niri_ipc::Transform::_90 => Transform::_90,
173 niri_ipc::Transform::_180 => Transform::_180,
174 niri_ipc::Transform::_270 => Transform::_270,
175 niri_ipc::Transform::Flipped => Transform::Flipped,
176 niri_ipc::Transform::Flipped90 => Transform::Flipped90,
177 niri_ipc::Transform::Flipped180 => Transform::Flipped180,
178 niri_ipc::Transform::Flipped270 => Transform::Flipped270,
179 }
180}
181
182pub fn send_scale_transform(
183 surface: &WlSurface,
184 data: &SurfaceData,
185 scale: output::Scale,
186 transform: Transform,
187) {
188 send_surface_state(surface, data, scale.integer_scale(), transform);
189 with_fractional_scale(data, |fractional| {
190 fractional.set_preferred_scale(scale.fractional_scale());
191 });
192}
193
194pub fn expand_home(path: &Path) -> anyhow::Result<Option<PathBuf>> {
195 if let Ok(rest) = path.strip_prefix("~") {
196 let dirs = UserDirs::new().context("error retrieving home directory")?;
197 Ok(Some([dirs.home_dir(), rest].iter().collect()))
198 } else {
199 Ok(None)
200 }
201}
202
203pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> {
204 let Some(path) = &config.screenshot_path else {
205 return Ok(None);
206 };
207
208 let format = CString::new(path.clone()).context("path must not contain nul bytes")?;
209
210 let mut buf = [0u8; 2048];
211 let mut path;
212 unsafe {
213 let time = libc::time(null_mut());
214 ensure!(time != -1, "error in time()");
215
216 let tm = libc::localtime(&time);
217 ensure!(!tm.is_null(), "error in localtime()");
218
219 let rv = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), format.as_ptr(), tm);
220 ensure!(rv != 0, "error formatting time");
221
222 path = PathBuf::from(OsStr::from_bytes(&buf[..rv]));
223 }
224
225 if let Some(expanded) = expand_home(&path).context("error expanding ~")? {
226 path = expanded;
227 }
228
229 Ok(Some(path))
230}
231
232pub fn write_png_rgba8(
233 w: impl Write,
234 width: u32,
235 height: u32,
236 pixels: &[u8],
237) -> Result<(), png::EncodingError> {
238 let mut encoder = png::Encoder::new(w, width, height);
239 encoder.set_color(png::ColorType::Rgba);
240 encoder.set_depth(png::BitDepth::Eight);
241
242 let mut writer = encoder.write_header()?;
243 writer.write_image_data(pixels)
244}
245
246pub fn output_matches_name(output: &Output, target: &str) -> bool {
247 let name = output.user_data().get::<OutputName>().unwrap();
248 name.matches(target)
249}
250
251pub fn is_laptop_panel(connector: &str) -> bool {
252 matches!(connector.get(..4), Some("eDP-" | "LVDS" | "DSI-"))
253}
254
255pub fn with_toplevel_role<T>(
256 toplevel: &ToplevelSurface,
257 f: impl FnOnce(&mut XdgToplevelSurfaceRoleAttributes) -> T,
258) -> T {
259 with_states(toplevel.wl_surface(), |states| {
260 let mut role = states
261 .data_map
262 .get::<XdgToplevelSurfaceData>()
263 .unwrap()
264 .lock()
265 .unwrap();
266
267 f(&mut role)
268 })
269}
270
271pub fn get_credentials_for_surface(surface: &WlSurface) -> Option<Credentials> {
272 let handle = surface.handle().upgrade()?;
273 let dh = DisplayHandle::from(handle);
274
275 let client = dh.get_client(surface.id()).ok()?;
276 let data = client.get_data::<ClientState>().unwrap();
277 if data.credentials_unknown {
278 return None;
279 }
280
281 client.get_credentials(&dh).ok()
282}
283
284pub fn ensure_min_max_size(mut x: i32, min_size: i32, max_size: i32) -> i32 {
285 if max_size > 0 {
286 x = min(x, max_size);
287 }
288 if min_size > 0 {
289 x = max(x, min_size);
290 }
291 x
292}
293
294pub fn ensure_min_max_size_maybe_zero(x: i32, min_size: i32, max_size: i32) -> i32 {
295 if x != 0 {
296 ensure_min_max_size(x, min_size, max_size)
297 } else if min_size > 0 && min_size == max_size {
298 min_size
299 } else {
300 0
301 }
302}
303
304pub fn clamp_preferring_top_left_in_area(
305 area: Rectangle<f64, Logical>,
306 rect: &mut Rectangle<f64, Logical>,
307) {
308 rect.loc.x = f64::min(rect.loc.x, area.loc.x + area.size.w - rect.size.w);
309 rect.loc.y = f64::min(rect.loc.y, area.loc.y + area.size.h - rect.size.h);
310
311 // Clamp by top and left last so it takes precedence.
312 rect.loc.x = f64::max(rect.loc.x, area.loc.x);
313 rect.loc.y = f64::max(rect.loc.y, area.loc.y);
314}
315
316pub fn center_preferring_top_left_in_area(
317 area: Rectangle<f64, Logical>,
318 size: Size<f64, Logical>,
319) -> Point<f64, Logical> {
320 let area_size = area.size.to_point();
321 let size = size.to_point();
322 let mut offset = (area_size - size).downscale(2.);
323 offset.x = f64::max(offset.x, 0.);
324 offset.y = f64::max(offset.y, 0.);
325 area.loc + offset
326}
327
328#[cfg(feature = "dbus")]
329pub fn show_screenshot_notification(image_path: Option<PathBuf>) -> anyhow::Result<()> {
330 use std::collections::HashMap;
331
332 use zbus::zvariant;
333
334 let conn = zbus::blocking::Connection::session()?;
335
336 // Try to add the screenshot as an image if possible.
337 let mut image_url = None;
338 if let Some(path) = image_path {
339 match path.canonicalize() {
340 Ok(path) => match url::Url::from_file_path(path) {
341 Ok(url) => {
342 image_url = Some(url);
343 }
344 Err(err) => {
345 warn!("error converting screenshot path to file url: {err:?}");
346 }
347 },
348 Err(err) => {
349 warn!("error canonicalizing screenshot path: {err:?}");
350 }
351 }
352 }
353
354 let actions: &[&str] = &[];
355
356 conn.call_method(
357 Some("org.freedesktop.Notifications"),
358 "/org/freedesktop/Notifications",
359 Some("org.freedesktop.Notifications"),
360 "Notify",
361 &(
362 "niri",
363 0u32,
364 image_url.as_ref().map(|url| url.as_str()).unwrap_or(""),
365 "Screenshot captured",
366 "You can paste the image from the clipboard.",
367 actions,
368 HashMap::from([
369 ("transient", zvariant::Value::Bool(true)),
370 ("urgency", zvariant::Value::U8(1)),
371 ]),
372 -1,
373 ),
374 )?;
375
376 Ok(())
377}
378
379#[inline(never)]
380pub fn cause_panic() {
381 let a = Duration::from_secs(1);
382 let b = Duration::from_secs(2);
383 let _ = a - b;
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 #[test]
391 fn test_clamp_preferring_top_left() {
392 fn check(
393 (ax, ay, aw, ah): (i32, i32, i32, i32),
394 (rx, ry, rw, rh): (i32, i32, i32, i32),
395 (ex, ey): (i32, i32),
396 ) {
397 let area = Rectangle::new(Point::from((ax, ay)), Size::from((aw, ah))).to_f64();
398 let mut rect = Rectangle::new(Point::from((rx, ry)), Size::from((rw, rh))).to_f64();
399 clamp_preferring_top_left_in_area(area, &mut rect);
400 assert_eq!(rect.loc, Point::from((ex, ey)).to_f64());
401 }
402
403 check((0, 0, 10, 20), (2, 3, 4, 5), (2, 3));
404 check((0, 0, 10, 20), (-2, 3, 4, 5), (0, 3));
405 check((0, 0, 10, 20), (2, -3, 4, 5), (2, 0));
406 check((0, 0, 10, 20), (-2, -3, 4, 5), (0, 0));
407
408 check((1, 1, 10, 20), (2, 3, 4, 5), (2, 3));
409 check((1, 1, 10, 20), (-2, 3, 4, 5), (1, 3));
410 check((1, 1, 10, 20), (2, -3, 4, 5), (2, 1));
411 check((1, 1, 10, 20), (-2, -3, 4, 5), (1, 1));
412
413 check((0, 0, 10, 20), (20, 3, 4, 5), (6, 3));
414 check((0, 0, 10, 20), (2, 30, 4, 5), (2, 15));
415 check((0, 0, 10, 20), (20, 30, 4, 5), (6, 15));
416
417 check((0, 0, 10, 20), (20, 30, 40, 5), (0, 15));
418 check((0, 0, 10, 20), (20, 30, 4, 50), (6, 0));
419 check((0, 0, 10, 20), (20, 30, 40, 50), (0, 0));
420 }
421}