forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB97dfd2bIvan Molodetskikh1 year ago2184 commits

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