forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBbbbd35eIvan Molodetskikh1 year ago1693 commits

mod.rs406 lines, 12.6 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 let version = env!("CARGO_PKG_VERSION");
87 let commit =
88 option_env!("NIRI_BUILD_COMMIT").unwrap_or(git_version!(fallback = "unknown commit"));
89
90 format!("{version} ({commit})")
91}
92
93pub fn get_monotonic_time() -> Duration {
94 let ts = clock_gettime(ClockId::Monotonic);
95 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
96}
97
98pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
99 rect.loc + rect.size.downscale(2).to_point()
100}
101
102pub fn center_f64(rect: Rectangle<f64, Logical>) -> Point<f64, Logical> {
103 rect.loc + rect.size.downscale(2.0).to_point()
104}
105
106/// Convert logical pixels to physical, rounding to physical pixels.
107pub fn to_physical_precise_round<N: Coordinate>(scale: f64, logical: impl Coordinate) -> N {
108 N::from_f64((logical.to_f64() * scale).round())
109}
110
111pub fn round_logical_in_physical(scale: f64, logical: f64) -> f64 {
112 (logical * scale).round() / scale
113}
114
115pub fn round_logical_in_physical_max1(scale: f64, logical: f64) -> f64 {
116 if logical == 0. {
117 return 0.;
118 }
119
120 (logical * scale).max(1.).round() / scale
121}
122
123pub fn output_size(output: &Output) -> Size<f64, Logical> {
124 let output_scale = output.current_scale().fractional_scale();
125 let output_transform = output.current_transform();
126 let output_mode = output.current_mode().unwrap();
127 let logical_size = output_mode.size.to_f64().to_logical(output_scale);
128 output_transform.transform_size(logical_size)
129}
130
131pub fn logical_output(output: &Output) -> niri_ipc::LogicalOutput {
132 let loc = output.current_location();
133 let size = output_size(output);
134 let transform = match output.current_transform() {
135 Transform::Normal => niri_ipc::Transform::Normal,
136 Transform::_90 => niri_ipc::Transform::_90,
137 Transform::_180 => niri_ipc::Transform::_180,
138 Transform::_270 => niri_ipc::Transform::_270,
139 Transform::Flipped => niri_ipc::Transform::Flipped,
140 Transform::Flipped90 => niri_ipc::Transform::Flipped90,
141 Transform::Flipped180 => niri_ipc::Transform::Flipped180,
142 Transform::Flipped270 => niri_ipc::Transform::Flipped270,
143 };
144 niri_ipc::LogicalOutput {
145 x: loc.x,
146 y: loc.y,
147 width: size.w as u32,
148 height: size.h as u32,
149 scale: output.current_scale().fractional_scale(),
150 transform,
151 }
152}
153
154pub fn ipc_transform_to_smithay(transform: niri_ipc::Transform) -> Transform {
155 match transform {
156 niri_ipc::Transform::Normal => Transform::Normal,
157 niri_ipc::Transform::_90 => Transform::_90,
158 niri_ipc::Transform::_180 => Transform::_180,
159 niri_ipc::Transform::_270 => Transform::_270,
160 niri_ipc::Transform::Flipped => Transform::Flipped,
161 niri_ipc::Transform::Flipped90 => Transform::Flipped90,
162 niri_ipc::Transform::Flipped180 => Transform::Flipped180,
163 niri_ipc::Transform::Flipped270 => Transform::Flipped270,
164 }
165}
166
167pub fn send_scale_transform(
168 surface: &WlSurface,
169 data: &SurfaceData,
170 scale: output::Scale,
171 transform: Transform,
172) {
173 send_surface_state(surface, data, scale.integer_scale(), transform);
174 with_fractional_scale(data, |fractional| {
175 fractional.set_preferred_scale(scale.fractional_scale());
176 });
177}
178
179pub fn expand_home(path: &Path) -> anyhow::Result<Option<PathBuf>> {
180 if let Ok(rest) = path.strip_prefix("~") {
181 let dirs = UserDirs::new().context("error retrieving home directory")?;
182 Ok(Some([dirs.home_dir(), rest].iter().collect()))
183 } else {
184 Ok(None)
185 }
186}
187
188pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> {
189 let Some(path) = &config.screenshot_path else {
190 return Ok(None);
191 };
192
193 let format = CString::new(path.clone()).context("path must not contain nul bytes")?;
194
195 let mut buf = [0u8; 2048];
196 let mut path;
197 unsafe {
198 let time = libc::time(null_mut());
199 ensure!(time != -1, "error in time()");
200
201 let tm = libc::localtime(&time);
202 ensure!(!tm.is_null(), "error in localtime()");
203
204 let rv = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), format.as_ptr(), tm);
205 ensure!(rv != 0, "error formatting time");
206
207 path = PathBuf::from(OsStr::from_bytes(&buf[..rv]));
208 }
209
210 if let Some(expanded) = expand_home(&path).context("error expanding ~")? {
211 path = expanded;
212 }
213
214 Ok(Some(path))
215}
216
217pub fn write_png_rgba8(
218 w: impl Write,
219 width: u32,
220 height: u32,
221 pixels: &[u8],
222) -> Result<(), png::EncodingError> {
223 let mut encoder = png::Encoder::new(w, width, height);
224 encoder.set_color(png::ColorType::Rgba);
225 encoder.set_depth(png::BitDepth::Eight);
226
227 let mut writer = encoder.write_header()?;
228 writer.write_image_data(pixels)
229}
230
231pub fn output_matches_name(output: &Output, target: &str) -> bool {
232 let name = output.user_data().get::<OutputName>().unwrap();
233 name.matches(target)
234}
235
236pub fn is_laptop_panel(connector: &str) -> bool {
237 matches!(connector.get(..4), Some("eDP-" | "LVDS" | "DSI-"))
238}
239
240pub fn with_toplevel_role<T>(
241 toplevel: &ToplevelSurface,
242 f: impl FnOnce(&mut XdgToplevelSurfaceRoleAttributes) -> T,
243) -> T {
244 with_states(toplevel.wl_surface(), |states| {
245 let mut role = states
246 .data_map
247 .get::<XdgToplevelSurfaceData>()
248 .unwrap()
249 .lock()
250 .unwrap();
251
252 f(&mut role)
253 })
254}
255
256pub fn get_credentials_for_surface(surface: &WlSurface) -> Option<Credentials> {
257 let handle = surface.handle().upgrade()?;
258 let dh = DisplayHandle::from(handle);
259
260 let client = dh.get_client(surface.id()).ok()?;
261 let data = client.get_data::<ClientState>().unwrap();
262 if data.credentials_unknown {
263 return None;
264 }
265
266 client.get_credentials(&dh).ok()
267}
268
269pub fn ensure_min_max_size(mut x: i32, min_size: i32, max_size: i32) -> i32 {
270 if max_size > 0 {
271 x = min(x, max_size);
272 }
273 if min_size > 0 {
274 x = max(x, min_size);
275 }
276 x
277}
278
279pub fn ensure_min_max_size_maybe_zero(x: i32, min_size: i32, max_size: i32) -> i32 {
280 if x != 0 {
281 ensure_min_max_size(x, min_size, max_size)
282 } else if min_size > 0 && min_size == max_size {
283 min_size
284 } else {
285 0
286 }
287}
288
289pub fn clamp_preferring_top_left_in_area(
290 area: Rectangle<f64, Logical>,
291 rect: &mut Rectangle<f64, Logical>,
292) {
293 rect.loc.x = f64::min(rect.loc.x, area.loc.x + area.size.w - rect.size.w);
294 rect.loc.y = f64::min(rect.loc.y, area.loc.y + area.size.h - rect.size.h);
295
296 // Clamp by top and left last so it takes precedence.
297 rect.loc.x = f64::max(rect.loc.x, area.loc.x);
298 rect.loc.y = f64::max(rect.loc.y, area.loc.y);
299}
300
301pub fn center_preferring_top_left_in_area(
302 area: Rectangle<f64, Logical>,
303 size: Size<f64, Logical>,
304) -> Point<f64, Logical> {
305 let area_size = area.size.to_point();
306 let size = size.to_point();
307 let mut offset = (area_size - size).downscale(2.);
308 offset.x = f64::max(offset.x, 0.);
309 offset.y = f64::max(offset.y, 0.);
310 area.loc + offset
311}
312
313#[cfg(feature = "dbus")]
314pub fn show_screenshot_notification(image_path: Option<PathBuf>) -> anyhow::Result<()> {
315 use std::collections::HashMap;
316
317 use zbus::zvariant;
318
319 let conn = zbus::blocking::Connection::session()?;
320
321 // Try to add the screenshot as an image if possible.
322 let mut image_url = None;
323 if let Some(path) = image_path {
324 match path.canonicalize() {
325 Ok(path) => match url::Url::from_file_path(path) {
326 Ok(url) => {
327 image_url = Some(url);
328 }
329 Err(err) => {
330 warn!("error converting screenshot path to file url: {err:?}");
331 }
332 },
333 Err(err) => {
334 warn!("error canonicalizing screenshot path: {err:?}");
335 }
336 }
337 }
338
339 let actions: &[&str] = &[];
340
341 conn.call_method(
342 Some("org.freedesktop.Notifications"),
343 "/org/freedesktop/Notifications",
344 Some("org.freedesktop.Notifications"),
345 "Notify",
346 &(
347 "niri",
348 0u32,
349 image_url.as_ref().map(|url| url.as_str()).unwrap_or(""),
350 "Screenshot captured",
351 "You can paste the image from the clipboard.",
352 actions,
353 HashMap::from([
354 ("transient", zvariant::Value::Bool(true)),
355 ("urgency", zvariant::Value::U8(1)),
356 ]),
357 -1,
358 ),
359 )?;
360
361 Ok(())
362}
363
364#[inline(never)]
365pub fn cause_panic() {
366 let a = Duration::from_secs(1);
367 let b = Duration::from_secs(2);
368 let _ = a - b;
369}
370
371#[cfg(test)]
372mod tests {
373 use super::*;
374
375 #[test]
376 fn test_clamp_preferring_top_left() {
377 fn check(
378 (ax, ay, aw, ah): (i32, i32, i32, i32),
379 (rx, ry, rw, rh): (i32, i32, i32, i32),
380 (ex, ey): (i32, i32),
381 ) {
382 let area = Rectangle::new(Point::from((ax, ay)), Size::from((aw, ah))).to_f64();
383 let mut rect = Rectangle::new(Point::from((rx, ry)), Size::from((rw, rh))).to_f64();
384 clamp_preferring_top_left_in_area(area, &mut rect);
385 assert_eq!(rect.loc, Point::from((ex, ey)).to_f64());
386 }
387
388 check((0, 0, 10, 20), (2, 3, 4, 5), (2, 3));
389 check((0, 0, 10, 20), (-2, 3, 4, 5), (0, 3));
390 check((0, 0, 10, 20), (2, -3, 4, 5), (2, 0));
391 check((0, 0, 10, 20), (-2, -3, 4, 5), (0, 0));
392
393 check((1, 1, 10, 20), (2, 3, 4, 5), (2, 3));
394 check((1, 1, 10, 20), (-2, 3, 4, 5), (1, 3));
395 check((1, 1, 10, 20), (2, -3, 4, 5), (2, 1));
396 check((1, 1, 10, 20), (-2, -3, 4, 5), (1, 1));
397
398 check((0, 0, 10, 20), (20, 3, 4, 5), (6, 3));
399 check((0, 0, 10, 20), (2, 30, 4, 5), (2, 15));
400 check((0, 0, 10, 20), (20, 30, 4, 5), (6, 15));
401
402 check((0, 0, 10, 20), (20, 30, 40, 5), (0, 15));
403 check((0, 0, 10, 20), (20, 30, 4, 50), (6, 0));
404 check((0, 0, 10, 20), (20, 30, 40, 50), (0, 0));
405 }
406}