forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

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