forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBad3847fIvan Molodetskikh1 year ago2457 commits

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