forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB99bf2dfIvan Molodetskikh1 year ago2106 commits

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