forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB53500dcTahinli1 month ago2998 commits

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