forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB2d82fddIvan Molodetskikh1 year ago2536 commits

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