forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB4eddcefIvan Molodetskikh1 year ago1772 commits

mod.rs413 lines, 12.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::input::pointer::CursorIcon;
16use smithay::output::{self, Output};
17use smithay::reexports::rustix::time::{clock_gettime, ClockId};
18use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
19use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
20use smithay::reexports::wayland_server::{DisplayHandle, Resource as _};
21use smithay::utils::{Coordinate, Logical, Point, Rectangle, Size, Transform};
22use smithay::wayland::compositor::{send_surface_state, with_states, SurfaceData};
23use smithay::wayland::fractional_scale::with_fractional_scale;
24use smithay::wayland::shell::xdg::{
25 ToplevelSurface, XdgToplevelSurfaceData, XdgToplevelSurfaceRoleAttributes,
26};
27use wayland_backend::server::Credentials;
28
29use crate::niri::ClientState;
30
31pub mod id;
32pub mod scale;
33pub mod spawning;
34pub mod transaction;
35pub mod watcher;
36
37pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
38
39bitflags! {
40 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41 pub struct ResizeEdge: u32 {
42 const TOP = 0b0001;
43 const BOTTOM = 0b0010;
44 const LEFT = 0b0100;
45 const RIGHT = 0b1000;
46
47 const TOP_LEFT = Self::TOP.bits() | Self::LEFT.bits();
48 const BOTTOM_LEFT = Self::BOTTOM.bits() | Self::LEFT.bits();
49
50 const TOP_RIGHT = Self::TOP.bits() | Self::RIGHT.bits();
51 const BOTTOM_RIGHT = Self::BOTTOM.bits() | Self::RIGHT.bits();
52
53 const LEFT_RIGHT = Self::LEFT.bits() | Self::RIGHT.bits();
54 const TOP_BOTTOM = Self::TOP.bits() | Self::BOTTOM.bits();
55 }
56}
57
58impl From<xdg_toplevel::ResizeEdge> for ResizeEdge {
59 #[inline]
60 fn from(x: xdg_toplevel::ResizeEdge) -> Self {
61 Self::from_bits(x as u32).unwrap()
62 }
63}
64
65impl ResizeEdge {
66 pub fn cursor_icon(self) -> CursorIcon {
67 match self {
68 Self::LEFT => CursorIcon::WResize,
69 Self::RIGHT => CursorIcon::EResize,
70 Self::TOP => CursorIcon::NResize,
71 Self::BOTTOM => CursorIcon::SResize,
72 Self::TOP_LEFT => CursorIcon::NwResize,
73 Self::TOP_RIGHT => CursorIcon::NeResize,
74 Self::BOTTOM_RIGHT => CursorIcon::SeResize,
75 Self::BOTTOM_LEFT => CursorIcon::SwResize,
76 _ => CursorIcon::Default,
77 }
78 }
79}
80
81pub fn version() -> String {
82 if let Some(v) = option_env!("NIRI_BUILD_VERSION_STRING") {
83 return String::from(v);
84 }
85
86 const MAJOR: &str = env!("CARGO_PKG_VERSION_MAJOR");
87 const MINOR: &str = env!("CARGO_PKG_VERSION_MINOR");
88 const PATCH: &str = env!("CARGO_PKG_VERSION_PATCH");
89
90 let commit =
91 option_env!("NIRI_BUILD_COMMIT").unwrap_or(git_version!(fallback = "unknown commit"));
92
93 if PATCH == "0" {
94 format!("{MAJOR}.{MINOR:0>2} ({commit})")
95 } else {
96 format!("{MAJOR}.{MINOR:0>2}.{PATCH} ({commit})")
97 }
98}
99
100pub fn get_monotonic_time() -> Duration {
101 let ts = clock_gettime(ClockId::Monotonic);
102 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
103}
104
105pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
106 rect.loc + rect.size.downscale(2).to_point()
107}
108
109pub fn center_f64(rect: Rectangle<f64, Logical>) -> Point<f64, Logical> {
110 rect.loc + rect.size.downscale(2.0).to_point()
111}
112
113/// Convert logical pixels to physical, rounding to physical pixels.
114pub fn to_physical_precise_round<N: Coordinate>(scale: f64, logical: impl Coordinate) -> N {
115 N::from_f64((logical.to_f64() * scale).round())
116}
117
118pub fn round_logical_in_physical(scale: f64, logical: f64) -> f64 {
119 (logical * scale).round() / scale
120}
121
122pub fn round_logical_in_physical_max1(scale: f64, logical: f64) -> f64 {
123 if logical == 0. {
124 return 0.;
125 }
126
127 (logical * scale).max(1.).round() / scale
128}
129
130pub fn output_size(output: &Output) -> Size<f64, Logical> {
131 let output_scale = output.current_scale().fractional_scale();
132 let output_transform = output.current_transform();
133 let output_mode = output.current_mode().unwrap();
134 let logical_size = output_mode.size.to_f64().to_logical(output_scale);
135 output_transform.transform_size(logical_size)
136}
137
138pub fn logical_output(output: &Output) -> niri_ipc::LogicalOutput {
139 let loc = output.current_location();
140 let size = output_size(output);
141 let transform = match output.current_transform() {
142 Transform::Normal => niri_ipc::Transform::Normal,
143 Transform::_90 => niri_ipc::Transform::_90,
144 Transform::_180 => niri_ipc::Transform::_180,
145 Transform::_270 => niri_ipc::Transform::_270,
146 Transform::Flipped => niri_ipc::Transform::Flipped,
147 Transform::Flipped90 => niri_ipc::Transform::Flipped90,
148 Transform::Flipped180 => niri_ipc::Transform::Flipped180,
149 Transform::Flipped270 => niri_ipc::Transform::Flipped270,
150 };
151 niri_ipc::LogicalOutput {
152 x: loc.x,
153 y: loc.y,
154 width: size.w as u32,
155 height: size.h as u32,
156 scale: output.current_scale().fractional_scale(),
157 transform,
158 }
159}
160
161pub fn ipc_transform_to_smithay(transform: niri_ipc::Transform) -> Transform {
162 match transform {
163 niri_ipc::Transform::Normal => Transform::Normal,
164 niri_ipc::Transform::_90 => Transform::_90,
165 niri_ipc::Transform::_180 => Transform::_180,
166 niri_ipc::Transform::_270 => Transform::_270,
167 niri_ipc::Transform::Flipped => Transform::Flipped,
168 niri_ipc::Transform::Flipped90 => Transform::Flipped90,
169 niri_ipc::Transform::Flipped180 => Transform::Flipped180,
170 niri_ipc::Transform::Flipped270 => Transform::Flipped270,
171 }
172}
173
174pub fn send_scale_transform(
175 surface: &WlSurface,
176 data: &SurfaceData,
177 scale: output::Scale,
178 transform: Transform,
179) {
180 send_surface_state(surface, data, scale.integer_scale(), transform);
181 with_fractional_scale(data, |fractional| {
182 fractional.set_preferred_scale(scale.fractional_scale());
183 });
184}
185
186pub fn expand_home(path: &Path) -> anyhow::Result<Option<PathBuf>> {
187 if let Ok(rest) = path.strip_prefix("~") {
188 let dirs = UserDirs::new().context("error retrieving home directory")?;
189 Ok(Some([dirs.home_dir(), rest].iter().collect()))
190 } else {
191 Ok(None)
192 }
193}
194
195pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> {
196 let Some(path) = &config.screenshot_path else {
197 return Ok(None);
198 };
199
200 let format = CString::new(path.clone()).context("path must not contain nul bytes")?;
201
202 let mut buf = [0u8; 2048];
203 let mut path;
204 unsafe {
205 let time = libc::time(null_mut());
206 ensure!(time != -1, "error in time()");
207
208 let tm = libc::localtime(&time);
209 ensure!(!tm.is_null(), "error in localtime()");
210
211 let rv = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), format.as_ptr(), tm);
212 ensure!(rv != 0, "error formatting time");
213
214 path = PathBuf::from(OsStr::from_bytes(&buf[..rv]));
215 }
216
217 if let Some(expanded) = expand_home(&path).context("error expanding ~")? {
218 path = expanded;
219 }
220
221 Ok(Some(path))
222}
223
224pub fn write_png_rgba8(
225 w: impl Write,
226 width: u32,
227 height: u32,
228 pixels: &[u8],
229) -> Result<(), png::EncodingError> {
230 let mut encoder = png::Encoder::new(w, width, height);
231 encoder.set_color(png::ColorType::Rgba);
232 encoder.set_depth(png::BitDepth::Eight);
233
234 let mut writer = encoder.write_header()?;
235 writer.write_image_data(pixels)
236}
237
238pub fn output_matches_name(output: &Output, target: &str) -> bool {
239 let name = output.user_data().get::<OutputName>().unwrap();
240 name.matches(target)
241}
242
243pub fn is_laptop_panel(connector: &str) -> bool {
244 matches!(connector.get(..4), Some("eDP-" | "LVDS" | "DSI-"))
245}
246
247pub fn with_toplevel_role<T>(
248 toplevel: &ToplevelSurface,
249 f: impl FnOnce(&mut XdgToplevelSurfaceRoleAttributes) -> T,
250) -> T {
251 with_states(toplevel.wl_surface(), |states| {
252 let mut role = states
253 .data_map
254 .get::<XdgToplevelSurfaceData>()
255 .unwrap()
256 .lock()
257 .unwrap();
258
259 f(&mut role)
260 })
261}
262
263pub fn get_credentials_for_surface(surface: &WlSurface) -> Option<Credentials> {
264 let handle = surface.handle().upgrade()?;
265 let dh = DisplayHandle::from(handle);
266
267 let client = dh.get_client(surface.id()).ok()?;
268 let data = client.get_data::<ClientState>().unwrap();
269 if data.credentials_unknown {
270 return None;
271 }
272
273 client.get_credentials(&dh).ok()
274}
275
276pub fn ensure_min_max_size(mut x: i32, min_size: i32, max_size: i32) -> i32 {
277 if max_size > 0 {
278 x = min(x, max_size);
279 }
280 if min_size > 0 {
281 x = max(x, min_size);
282 }
283 x
284}
285
286pub fn ensure_min_max_size_maybe_zero(x: i32, min_size: i32, max_size: i32) -> i32 {
287 if x != 0 {
288 ensure_min_max_size(x, min_size, max_size)
289 } else if min_size > 0 && min_size == max_size {
290 min_size
291 } else {
292 0
293 }
294}
295
296pub fn clamp_preferring_top_left_in_area(
297 area: Rectangle<f64, Logical>,
298 rect: &mut Rectangle<f64, Logical>,
299) {
300 rect.loc.x = f64::min(rect.loc.x, area.loc.x + area.size.w - rect.size.w);
301 rect.loc.y = f64::min(rect.loc.y, area.loc.y + area.size.h - rect.size.h);
302
303 // Clamp by top and left last so it takes precedence.
304 rect.loc.x = f64::max(rect.loc.x, area.loc.x);
305 rect.loc.y = f64::max(rect.loc.y, area.loc.y);
306}
307
308pub fn center_preferring_top_left_in_area(
309 area: Rectangle<f64, Logical>,
310 size: Size<f64, Logical>,
311) -> Point<f64, Logical> {
312 let area_size = area.size.to_point();
313 let size = size.to_point();
314 let mut offset = (area_size - size).downscale(2.);
315 offset.x = f64::max(offset.x, 0.);
316 offset.y = f64::max(offset.y, 0.);
317 area.loc + offset
318}
319
320#[cfg(feature = "dbus")]
321pub fn show_screenshot_notification(image_path: Option<PathBuf>) -> anyhow::Result<()> {
322 use std::collections::HashMap;
323
324 use zbus::zvariant;
325
326 let conn = zbus::blocking::Connection::session()?;
327
328 // Try to add the screenshot as an image if possible.
329 let mut image_url = None;
330 if let Some(path) = image_path {
331 match path.canonicalize() {
332 Ok(path) => match url::Url::from_file_path(path) {
333 Ok(url) => {
334 image_url = Some(url);
335 }
336 Err(err) => {
337 warn!("error converting screenshot path to file url: {err:?}");
338 }
339 },
340 Err(err) => {
341 warn!("error canonicalizing screenshot path: {err:?}");
342 }
343 }
344 }
345
346 let actions: &[&str] = &[];
347
348 conn.call_method(
349 Some("org.freedesktop.Notifications"),
350 "/org/freedesktop/Notifications",
351 Some("org.freedesktop.Notifications"),
352 "Notify",
353 &(
354 "niri",
355 0u32,
356 image_url.as_ref().map(|url| url.as_str()).unwrap_or(""),
357 "Screenshot captured",
358 "You can paste the image from the clipboard.",
359 actions,
360 HashMap::from([
361 ("transient", zvariant::Value::Bool(true)),
362 ("urgency", zvariant::Value::U8(1)),
363 ]),
364 -1,
365 ),
366 )?;
367
368 Ok(())
369}
370
371#[inline(never)]
372pub fn cause_panic() {
373 let a = Duration::from_secs(1);
374 let b = Duration::from_secs(2);
375 let _ = a - b;
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381
382 #[test]
383 fn test_clamp_preferring_top_left() {
384 fn check(
385 (ax, ay, aw, ah): (i32, i32, i32, i32),
386 (rx, ry, rw, rh): (i32, i32, i32, i32),
387 (ex, ey): (i32, i32),
388 ) {
389 let area = Rectangle::new(Point::from((ax, ay)), Size::from((aw, ah))).to_f64();
390 let mut rect = Rectangle::new(Point::from((rx, ry)), Size::from((rw, rh))).to_f64();
391 clamp_preferring_top_left_in_area(area, &mut rect);
392 assert_eq!(rect.loc, Point::from((ex, ey)).to_f64());
393 }
394
395 check((0, 0, 10, 20), (2, 3, 4, 5), (2, 3));
396 check((0, 0, 10, 20), (-2, 3, 4, 5), (0, 3));
397 check((0, 0, 10, 20), (2, -3, 4, 5), (2, 0));
398 check((0, 0, 10, 20), (-2, -3, 4, 5), (0, 0));
399
400 check((1, 1, 10, 20), (2, 3, 4, 5), (2, 3));
401 check((1, 1, 10, 20), (-2, 3, 4, 5), (1, 3));
402 check((1, 1, 10, 20), (2, -3, 4, 5), (2, 1));
403 check((1, 1, 10, 20), (-2, -3, 4, 5), (1, 1));
404
405 check((0, 0, 10, 20), (20, 3, 4, 5), (6, 3));
406 check((0, 0, 10, 20), (2, 30, 4, 5), (2, 15));
407 check((0, 0, 10, 20), (20, 30, 4, 5), (6, 15));
408
409 check((0, 0, 10, 20), (20, 30, 40, 5), (0, 15));
410 check((0, 0, 10, 20), (20, 30, 4, 50), (6, 0));
411 check((0, 0, 10, 20), (20, 30, 40, 50), (0, 0));
412 }
413}