forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB90ef202Ivan Molodetskikh1 year ago2349 commits

mod.rs501 lines, 17.0 KiBHistoryRawDownload
1use std::cmp::{max, min};
2use std::f64;
3use std::ffi::{CString, OsStr};
4use std::io::Write;
5use std::os::unix::prelude::OsStrExt;
6use std::path::{Path, PathBuf};
7use std::ptr::null_mut;
8use std::sync::atomic::AtomicBool;
9use std::time::Duration;
10
11use anyhow::{ensure, Context};
12use bitflags::bitflags;
13use directories::UserDirs;
14use git_version::git_version;
15use niri_config::{Config, OutputName};
16use smithay::backend::renderer::utils::with_renderer_surface_state;
17use smithay::input::pointer::CursorIcon;
18use smithay::output::{self, Output};
19use smithay::reexports::rustix::time::{clock_gettime, ClockId};
20use smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1;
21use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
22use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
23use smithay::reexports::wayland_server::{DisplayHandle, Resource as _};
24use smithay::utils::{Coordinate, Logical, Point, Rectangle, Size, Transform};
25use smithay::wayland::compositor::{send_surface_state, with_states, SurfaceData};
26use smithay::wayland::fractional_scale::with_fractional_scale;
27use smithay::wayland::shell::xdg::{
28 ToplevelSurface, XdgToplevelSurfaceData, XdgToplevelSurfaceRoleAttributes,
29};
30use wayland_backend::server::Credentials;
31
32use crate::handlers::KdeDecorationsModeState;
33use crate::niri::ClientState;
34
35pub mod id;
36pub mod scale;
37pub mod signals;
38pub mod spawning;
39pub mod transaction;
40pub mod watcher;
41pub mod xwayland;
42
43pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
44
45bitflags! {
46 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47 pub struct ResizeEdge: u32 {
48 const TOP = 0b0001;
49 const BOTTOM = 0b0010;
50 const LEFT = 0b0100;
51 const RIGHT = 0b1000;
52
53 const TOP_LEFT = Self::TOP.bits() | Self::LEFT.bits();
54 const BOTTOM_LEFT = Self::BOTTOM.bits() | Self::LEFT.bits();
55
56 const TOP_RIGHT = Self::TOP.bits() | Self::RIGHT.bits();
57 const BOTTOM_RIGHT = Self::BOTTOM.bits() | Self::RIGHT.bits();
58
59 const LEFT_RIGHT = Self::LEFT.bits() | Self::RIGHT.bits();
60 const TOP_BOTTOM = Self::TOP.bits() | Self::BOTTOM.bits();
61 }
62}
63
64impl From<xdg_toplevel::ResizeEdge> for ResizeEdge {
65 #[inline]
66 fn from(x: xdg_toplevel::ResizeEdge) -> Self {
67 Self::from_bits(x as u32).unwrap()
68 }
69}
70
71impl ResizeEdge {
72 pub fn cursor_icon(self) -> CursorIcon {
73 match self {
74 Self::LEFT => CursorIcon::WResize,
75 Self::RIGHT => CursorIcon::EResize,
76 Self::TOP => CursorIcon::NResize,
77 Self::BOTTOM => CursorIcon::SResize,
78 Self::TOP_LEFT => CursorIcon::NwResize,
79 Self::TOP_RIGHT => CursorIcon::NeResize,
80 Self::BOTTOM_RIGHT => CursorIcon::SeResize,
81 Self::BOTTOM_LEFT => CursorIcon::SwResize,
82 _ => CursorIcon::Default,
83 }
84 }
85}
86
87pub fn version() -> String {
88 if let Some(v) = option_env!("NIRI_BUILD_VERSION_STRING") {
89 return String::from(v);
90 }
91
92 const MAJOR: &str = env!("CARGO_PKG_VERSION_MAJOR");
93 const MINOR: &str = env!("CARGO_PKG_VERSION_MINOR");
94 const PATCH: &str = env!("CARGO_PKG_VERSION_PATCH");
95
96 let commit =
97 option_env!("NIRI_BUILD_COMMIT").unwrap_or(git_version!(fallback = "unknown commit"));
98
99 if PATCH == "0" {
100 format!("{MAJOR}.{MINOR:0>2} ({commit})")
101 } else {
102 format!("{MAJOR}.{MINOR:0>2}.{PATCH} ({commit})")
103 }
104}
105
106pub fn get_monotonic_time() -> Duration {
107 let ts = clock_gettime(ClockId::Monotonic);
108 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
109}
110
111pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
112 rect.loc + rect.size.downscale(2).to_point()
113}
114
115pub fn center_f64(rect: Rectangle<f64, Logical>) -> Point<f64, Logical> {
116 rect.loc + rect.size.downscale(2.0).to_point()
117}
118
119/// Convert logical pixels to physical, rounding to physical pixels.
120pub fn to_physical_precise_round<N: Coordinate>(scale: f64, logical: impl Coordinate) -> N {
121 N::from_f64((logical.to_f64() * scale).round())
122}
123
124pub fn round_logical_in_physical(scale: f64, logical: f64) -> f64 {
125 (logical * scale).round() / scale
126}
127
128pub fn round_logical_in_physical_max1(scale: f64, logical: f64) -> f64 {
129 if logical == 0. {
130 return 0.;
131 }
132
133 (logical * scale).max(1.).round() / scale
134}
135
136pub fn floor_logical_in_physical_max1(scale: f64, logical: f64) -> f64 {
137 if logical == 0. {
138 return 0.;
139 }
140
141 (logical * scale).max(1.).floor() / scale
142}
143
144pub fn output_size(output: &Output) -> Size<f64, Logical> {
145 let output_scale = output.current_scale().fractional_scale();
146 let output_transform = output.current_transform();
147 let output_mode = output.current_mode().unwrap();
148 let logical_size = output_mode.size.to_f64().to_logical(output_scale);
149 output_transform.transform_size(logical_size)
150}
151
152pub fn logical_output(output: &Output) -> niri_ipc::LogicalOutput {
153 let loc = output.current_location();
154 let size = output_size(output);
155 let transform = match output.current_transform() {
156 Transform::Normal => niri_ipc::Transform::Normal,
157 Transform::_90 => niri_ipc::Transform::_90,
158 Transform::_180 => niri_ipc::Transform::_180,
159 Transform::_270 => niri_ipc::Transform::_270,
160 Transform::Flipped => niri_ipc::Transform::Flipped,
161 Transform::Flipped90 => niri_ipc::Transform::Flipped90,
162 Transform::Flipped180 => niri_ipc::Transform::Flipped180,
163 Transform::Flipped270 => niri_ipc::Transform::Flipped270,
164 };
165 niri_ipc::LogicalOutput {
166 x: loc.x,
167 y: loc.y,
168 width: size.w as u32,
169 height: size.h as u32,
170 scale: output.current_scale().fractional_scale(),
171 transform,
172 }
173}
174
175pub fn ipc_transform_to_smithay(transform: niri_ipc::Transform) -> Transform {
176 match transform {
177 niri_ipc::Transform::Normal => Transform::Normal,
178 niri_ipc::Transform::_90 => Transform::_90,
179 niri_ipc::Transform::_180 => Transform::_180,
180 niri_ipc::Transform::_270 => Transform::_270,
181 niri_ipc::Transform::Flipped => Transform::Flipped,
182 niri_ipc::Transform::Flipped90 => Transform::Flipped90,
183 niri_ipc::Transform::Flipped180 => Transform::Flipped180,
184 niri_ipc::Transform::Flipped270 => Transform::Flipped270,
185 }
186}
187
188pub fn is_mapped(surface: &WlSurface) -> bool {
189 // None if the surface hadn't committed yet.
190 with_renderer_surface_state(surface, |state| state.buffer().is_some()).unwrap_or(false)
191}
192
193pub fn send_scale_transform(
194 surface: &WlSurface,
195 data: &SurfaceData,
196 scale: output::Scale,
197 transform: Transform,
198) {
199 send_surface_state(surface, data, scale.integer_scale(), transform);
200 with_fractional_scale(data, |fractional| {
201 fractional.set_preferred_scale(scale.fractional_scale());
202 });
203}
204
205pub fn expand_home(path: &Path) -> anyhow::Result<Option<PathBuf>> {
206 if let Ok(rest) = path.strip_prefix("~") {
207 let dirs = UserDirs::new().context("error retrieving home directory")?;
208 Ok(Some([dirs.home_dir(), rest].iter().collect()))
209 } else {
210 Ok(None)
211 }
212}
213
214pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> {
215 let Some(path) = &config.screenshot_path else {
216 return Ok(None);
217 };
218
219 let format = CString::new(path.clone()).context("path must not contain nul bytes")?;
220
221 let mut buf = [0u8; 2048];
222 let mut path;
223 unsafe {
224 let time = libc::time(null_mut());
225 ensure!(time != -1, "error in time()");
226
227 let tm = libc::localtime(&time);
228 ensure!(!tm.is_null(), "error in localtime()");
229
230 let rv = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), format.as_ptr(), tm);
231 ensure!(rv != 0, "error formatting time");
232
233 path = PathBuf::from(OsStr::from_bytes(&buf[..rv]));
234 }
235
236 if let Some(expanded) = expand_home(&path).context("error expanding ~")? {
237 path = expanded;
238 }
239
240 Ok(Some(path))
241}
242
243pub fn write_png_rgba8(
244 w: impl Write,
245 width: u32,
246 height: u32,
247 pixels: &[u8],
248) -> Result<(), png::EncodingError> {
249 let mut encoder = png::Encoder::new(w, width, height);
250 encoder.set_color(png::ColorType::Rgba);
251 encoder.set_depth(png::BitDepth::Eight);
252
253 let mut writer = encoder.write_header()?;
254 writer.write_image_data(pixels)
255}
256
257pub fn output_matches_name(output: &Output, target: &str) -> bool {
258 let name = output.user_data().get::<OutputName>().unwrap();
259 name.matches(target)
260}
261
262pub fn is_laptop_panel(connector: &str) -> bool {
263 matches!(connector.get(..4), Some("eDP-" | "LVDS" | "DSI-"))
264}
265
266pub fn with_toplevel_role<T>(
267 toplevel: &ToplevelSurface,
268 f: impl FnOnce(&mut XdgToplevelSurfaceRoleAttributes) -> T,
269) -> T {
270 with_states(toplevel.wl_surface(), |states| {
271 let mut role = states
272 .data_map
273 .get::<XdgToplevelSurfaceData>()
274 .unwrap()
275 .lock()
276 .unwrap();
277
278 f(&mut role)
279 })
280}
281
282pub fn update_tiled_state(
283 toplevel: &ToplevelSurface,
284 prefer_no_csd: bool,
285 force_tiled: Option<bool>,
286) {
287 // Determine the default value for our tiled state. The idea is to use the tiled state to
288 // make windows rectangular even if they don't support xdg-decoration (e.g. GTK).
289 //
290 // If the user prefers no CSD, it's a reasonable assumption that they would prefer to get
291 // rid of the various client-side rounded corners also by using the tiled state.
292 let should_tile = || {
293 // Figure out if the client bound any decoration globals for this window. In this case,
294 // the pending decoration mode will be set to something (we always set it upon binding the
295 // global and never reset to None).
296 //
297 // If the client bound a decoration global, use the mode that we negotiated. This way,
298 // changing the decoration mode on the client at runtime will synchronize with the
299 // default tiled state.
300 if let Some(mode) = toplevel.with_pending_state(|state| state.decoration_mode) {
301 mode == zxdg_toplevel_decoration_v1::Mode::ServerSide
302 } else if let Some(mode) = with_states(toplevel.wl_surface(), |states| {
303 states.data_map.get::<KdeDecorationsModeState>().cloned()
304 }) {
305 // Actually, make the KDE decoration overridable with prefer_no_csd. GTK 3 likes to
306 // always request CSD through it, and we want prefer_no_csd to set the tiled state
307 // automatically for GTK 3. Also, unlike xdg-decoration, KDE decoration is not
308 // synchronized to commits, so that argument is less important.
309 mode.is_server() || prefer_no_csd
310 } else {
311 // The client doesn't see or doesn't care about the decoration protocols. In this
312 // case, use the current prefer_no_csd value as the user's intention.
313 //
314 // This is a bit weird because it makes it seem like prefer_no_csd can apply live,
315 // while that isn't really the case. That's because prefer_no_csd controls two separate
316 // things: whether the client sees the decoration globals, and the tiled state.
317 //
318 // A more accurate way would perhaps be to check if the client cannot see the
319 // decoration globals, and in this case behave as if prefer_no_csd was false. However,
320 // this also regresses the common case of GTK 4 applications that do not react to
321 // xdg-decoration in any way, and therefore the tiled state *is* the "no CSD" mode from
322 // the user's perspective, so by artificially gating it we would artificially make it
323 // impossible to apply it live for GTK 4 applications.
324 prefer_no_csd
325 }
326 };
327
328 let should_tile = force_tiled.unwrap_or_else(should_tile);
329
330 toplevel.with_pending_state(|state| {
331 if should_tile {
332 state.states.set(xdg_toplevel::State::TiledLeft);
333 state.states.set(xdg_toplevel::State::TiledRight);
334 state.states.set(xdg_toplevel::State::TiledTop);
335 state.states.set(xdg_toplevel::State::TiledBottom);
336 } else {
337 state.states.unset(xdg_toplevel::State::TiledLeft);
338 state.states.unset(xdg_toplevel::State::TiledRight);
339 state.states.unset(xdg_toplevel::State::TiledTop);
340 state.states.unset(xdg_toplevel::State::TiledBottom);
341 }
342 });
343}
344
345pub fn get_credentials_for_surface(surface: &WlSurface) -> Option<Credentials> {
346 let handle = surface.handle().upgrade()?;
347 let dh = DisplayHandle::from(handle);
348
349 let client = dh.get_client(surface.id()).ok()?;
350 let data = client.get_data::<ClientState>().unwrap();
351 if data.credentials_unknown {
352 return None;
353 }
354
355 client.get_credentials(&dh).ok()
356}
357
358pub fn ensure_min_max_size(mut x: i32, min_size: i32, max_size: i32) -> i32 {
359 if max_size > 0 {
360 x = min(x, max_size);
361 }
362 if min_size > 0 {
363 x = max(x, min_size);
364 }
365 x
366}
367
368pub fn ensure_min_max_size_maybe_zero(x: i32, min_size: i32, max_size: i32) -> i32 {
369 if x != 0 {
370 ensure_min_max_size(x, min_size, max_size)
371 } else if min_size > 0 && min_size == max_size {
372 min_size
373 } else {
374 0
375 }
376}
377
378pub fn clamp_preferring_top_left_in_area(
379 area: Rectangle<f64, Logical>,
380 rect: &mut Rectangle<f64, Logical>,
381) {
382 rect.loc.x = f64::min(rect.loc.x, area.loc.x + area.size.w - rect.size.w);
383 rect.loc.y = f64::min(rect.loc.y, area.loc.y + area.size.h - rect.size.h);
384
385 // Clamp by top and left last so it takes precedence.
386 rect.loc.x = f64::max(rect.loc.x, area.loc.x);
387 rect.loc.y = f64::max(rect.loc.y, area.loc.y);
388}
389
390pub fn center_preferring_top_left_in_area(
391 area: Rectangle<f64, Logical>,
392 size: Size<f64, Logical>,
393) -> Point<f64, Logical> {
394 let area_size = area.size.to_point();
395 let size = size.to_point();
396 let mut offset = (area_size - size).downscale(2.);
397 offset.x = f64::max(offset.x, 0.);
398 offset.y = f64::max(offset.y, 0.);
399 area.loc + offset
400}
401
402pub fn baba_is_float_offset(now: Duration, view_height: f64) -> f64 {
403 let now = now.as_secs_f64();
404 let amplitude = view_height / 96.;
405 amplitude * ((f64::consts::TAU * now / 3.6).sin() - 1.)
406}
407
408#[cfg(feature = "dbus")]
409pub fn show_screenshot_notification(image_path: Option<PathBuf>) -> anyhow::Result<()> {
410 use std::collections::HashMap;
411
412 use zbus::zvariant;
413
414 let conn = zbus::blocking::Connection::session()?;
415
416 // Try to add the screenshot as an image if possible.
417 let mut image_url = None;
418 if let Some(path) = image_path {
419 match path.canonicalize() {
420 Ok(path) => match url::Url::from_file_path(path) {
421 Ok(url) => {
422 image_url = Some(url);
423 }
424 Err(err) => {
425 warn!("error converting screenshot path to file url: {err:?}");
426 }
427 },
428 Err(err) => {
429 warn!("error canonicalizing screenshot path: {err:?}");
430 }
431 }
432 }
433
434 let actions: &[&str] = &[];
435
436 conn.call_method(
437 Some("org.freedesktop.Notifications"),
438 "/org/freedesktop/Notifications",
439 Some("org.freedesktop.Notifications"),
440 "Notify",
441 &(
442 "niri",
443 0u32,
444 image_url.as_ref().map(|url| url.as_str()).unwrap_or(""),
445 "Screenshot captured",
446 "You can paste the image from the clipboard.",
447 actions,
448 HashMap::from([
449 ("transient", zvariant::Value::Bool(true)),
450 ("urgency", zvariant::Value::U8(1)),
451 ]),
452 -1,
453 ),
454 )?;
455
456 Ok(())
457}
458
459#[inline(never)]
460pub fn cause_panic() {
461 let a = Duration::from_secs(1);
462 let b = Duration::from_secs(2);
463 let _ = a - b;
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469
470 #[test]
471 fn test_clamp_preferring_top_left() {
472 fn check(
473 (ax, ay, aw, ah): (i32, i32, i32, i32),
474 (rx, ry, rw, rh): (i32, i32, i32, i32),
475 (ex, ey): (i32, i32),
476 ) {
477 let area = Rectangle::new(Point::from((ax, ay)), Size::from((aw, ah))).to_f64();
478 let mut rect = Rectangle::new(Point::from((rx, ry)), Size::from((rw, rh))).to_f64();
479 clamp_preferring_top_left_in_area(area, &mut rect);
480 assert_eq!(rect.loc, Point::from((ex, ey)).to_f64());
481 }
482
483 check((0, 0, 10, 20), (2, 3, 4, 5), (2, 3));
484 check((0, 0, 10, 20), (-2, 3, 4, 5), (0, 3));
485 check((0, 0, 10, 20), (2, -3, 4, 5), (2, 0));
486 check((0, 0, 10, 20), (-2, -3, 4, 5), (0, 0));
487
488 check((1, 1, 10, 20), (2, 3, 4, 5), (2, 3));
489 check((1, 1, 10, 20), (-2, 3, 4, 5), (1, 3));
490 check((1, 1, 10, 20), (2, -3, 4, 5), (2, 1));
491 check((1, 1, 10, 20), (-2, -3, 4, 5), (1, 1));
492
493 check((0, 0, 10, 20), (20, 3, 4, 5), (6, 3));
494 check((0, 0, 10, 20), (2, 30, 4, 5), (2, 15));
495 check((0, 0, 10, 20), (20, 30, 4, 5), (6, 15));
496
497 check((0, 0, 10, 20), (20, 30, 40, 5), (0, 15));
498 check((0, 0, 10, 20), (20, 30, 4, 50), (6, 0));
499 check((0, 0, 10, 20), (20, 30, 40, 50), (0, 0));
500 }
501}