forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBfa2baceMaximilian Huber1 year ago1550 commits

mod.rs300 lines, 9.4 KiBHistoryRawDownload
1use std::ffi::{CString, OsStr};
2use std::io::Write;
3use std::os::unix::prelude::OsStrExt;
4use std::path::{Path, PathBuf};
5use std::ptr::null_mut;
6use std::sync::atomic::AtomicBool;
7use std::time::Duration;
8
9use anyhow::{ensure, Context};
10use bitflags::bitflags;
11use directories::UserDirs;
12use git_version::git_version;
13use niri_config::{Config, OutputName};
14use smithay::input::pointer::CursorIcon;
15use smithay::output::{self, Output};
16use smithay::reexports::rustix::time::{clock_gettime, ClockId};
17use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
18use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
19use smithay::reexports::wayland_server::{DisplayHandle, Resource as _};
20use smithay::utils::{Coordinate, Logical, Point, Rectangle, Size, Transform};
21use smithay::wayland::compositor::{send_surface_state, with_states, SurfaceData};
22use smithay::wayland::fractional_scale::with_fractional_scale;
23use smithay::wayland::shell::xdg::{
24 ToplevelSurface, XdgToplevelSurfaceData, XdgToplevelSurfaceRoleAttributes,
25};
26use wayland_backend::server::Credentials;
27
28use crate::niri::ClientState;
29
30pub mod id;
31pub mod scale;
32pub mod spawning;
33pub mod transaction;
34pub mod watcher;
35
36pub static IS_SYSTEMD_SERVICE: AtomicBool = AtomicBool::new(false);
37
38bitflags! {
39 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40 pub struct ResizeEdge: u32 {
41 const TOP = 0b0001;
42 const BOTTOM = 0b0010;
43 const LEFT = 0b0100;
44 const RIGHT = 0b1000;
45
46 const TOP_LEFT = Self::TOP.bits() | Self::LEFT.bits();
47 const BOTTOM_LEFT = Self::BOTTOM.bits() | Self::LEFT.bits();
48
49 const TOP_RIGHT = Self::TOP.bits() | Self::RIGHT.bits();
50 const BOTTOM_RIGHT = Self::BOTTOM.bits() | Self::RIGHT.bits();
51
52 const LEFT_RIGHT = Self::LEFT.bits() | Self::RIGHT.bits();
53 const TOP_BOTTOM = Self::TOP.bits() | Self::BOTTOM.bits();
54 }
55}
56
57impl From<xdg_toplevel::ResizeEdge> for ResizeEdge {
58 #[inline]
59 fn from(x: xdg_toplevel::ResizeEdge) -> Self {
60 Self::from_bits(x as u32).unwrap()
61 }
62}
63
64impl ResizeEdge {
65 pub fn cursor_icon(self) -> CursorIcon {
66 match self {
67 Self::LEFT => CursorIcon::WResize,
68 Self::RIGHT => CursorIcon::EResize,
69 Self::TOP => CursorIcon::NResize,
70 Self::BOTTOM => CursorIcon::SResize,
71 Self::TOP_LEFT => CursorIcon::NwResize,
72 Self::TOP_RIGHT => CursorIcon::NeResize,
73 Self::BOTTOM_RIGHT => CursorIcon::SeResize,
74 Self::BOTTOM_LEFT => CursorIcon::SwResize,
75 _ => CursorIcon::Default,
76 }
77 }
78}
79
80pub fn version() -> String {
81 format!(
82 "{} ({})",
83 env!("CARGO_PKG_VERSION"),
84 git_version!(fallback = "unknown commit"),
85 )
86}
87
88pub fn get_monotonic_time() -> Duration {
89 let ts = clock_gettime(ClockId::Monotonic);
90 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
91}
92
93pub fn center(rect: Rectangle<i32, Logical>) -> Point<i32, Logical> {
94 rect.loc + rect.size.downscale(2).to_point()
95}
96
97pub fn center_f64(rect: Rectangle<f64, Logical>) -> Point<f64, Logical> {
98 rect.loc + rect.size.downscale(2.0).to_point()
99}
100
101/// Convert logical pixels to physical, rounding to physical pixels.
102pub fn to_physical_precise_round<N: Coordinate>(scale: f64, logical: impl Coordinate) -> N {
103 N::from_f64((logical.to_f64() * scale).round())
104}
105
106pub fn round_logical_in_physical(scale: f64, logical: f64) -> f64 {
107 (logical * scale).round() / scale
108}
109
110pub fn round_logical_in_physical_max1(scale: f64, logical: f64) -> f64 {
111 if logical == 0. {
112 return 0.;
113 }
114
115 (logical * scale).max(1.).round() / scale
116}
117
118pub fn output_size(output: &Output) -> Size<f64, Logical> {
119 let output_scale = output.current_scale().fractional_scale();
120 let output_transform = output.current_transform();
121 let output_mode = output.current_mode().unwrap();
122 let logical_size = output_mode.size.to_f64().to_logical(output_scale);
123 output_transform.transform_size(logical_size)
124}
125
126pub fn logical_output(output: &Output) -> niri_ipc::LogicalOutput {
127 let loc = output.current_location();
128 let size = output_size(output);
129 let transform = match output.current_transform() {
130 Transform::Normal => niri_ipc::Transform::Normal,
131 Transform::_90 => niri_ipc::Transform::_90,
132 Transform::_180 => niri_ipc::Transform::_180,
133 Transform::_270 => niri_ipc::Transform::_270,
134 Transform::Flipped => niri_ipc::Transform::Flipped,
135 Transform::Flipped90 => niri_ipc::Transform::Flipped90,
136 Transform::Flipped180 => niri_ipc::Transform::Flipped180,
137 Transform::Flipped270 => niri_ipc::Transform::Flipped270,
138 };
139 niri_ipc::LogicalOutput {
140 x: loc.x,
141 y: loc.y,
142 width: size.w as u32,
143 height: size.h as u32,
144 scale: output.current_scale().fractional_scale(),
145 transform,
146 }
147}
148
149pub fn ipc_transform_to_smithay(transform: niri_ipc::Transform) -> Transform {
150 match transform {
151 niri_ipc::Transform::Normal => Transform::Normal,
152 niri_ipc::Transform::_90 => Transform::_90,
153 niri_ipc::Transform::_180 => Transform::_180,
154 niri_ipc::Transform::_270 => Transform::_270,
155 niri_ipc::Transform::Flipped => Transform::Flipped,
156 niri_ipc::Transform::Flipped90 => Transform::Flipped90,
157 niri_ipc::Transform::Flipped180 => Transform::Flipped180,
158 niri_ipc::Transform::Flipped270 => Transform::Flipped270,
159 }
160}
161
162pub fn send_scale_transform(
163 surface: &WlSurface,
164 data: &SurfaceData,
165 scale: output::Scale,
166 transform: Transform,
167) {
168 send_surface_state(surface, data, scale.integer_scale(), transform);
169 with_fractional_scale(data, |fractional| {
170 fractional.set_preferred_scale(scale.fractional_scale());
171 });
172}
173
174pub fn expand_home(path: &Path) -> anyhow::Result<Option<PathBuf>> {
175 if let Ok(rest) = path.strip_prefix("~") {
176 let dirs = UserDirs::new().context("error retrieving home directory")?;
177 Ok(Some([dirs.home_dir(), rest].iter().collect()))
178 } else {
179 Ok(None)
180 }
181}
182
183pub fn make_screenshot_path(config: &Config) -> anyhow::Result<Option<PathBuf>> {
184 let Some(path) = &config.screenshot_path else {
185 return Ok(None);
186 };
187
188 let format = CString::new(path.clone()).context("path must not contain nul bytes")?;
189
190 let mut buf = [0u8; 2048];
191 let mut path;
192 unsafe {
193 let time = libc::time(null_mut());
194 ensure!(time != -1, "error in time()");
195
196 let tm = libc::localtime(&time);
197 ensure!(!tm.is_null(), "error in localtime()");
198
199 let rv = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), format.as_ptr(), tm);
200 ensure!(rv != 0, "error formatting time");
201
202 path = PathBuf::from(OsStr::from_bytes(&buf[..rv]));
203 }
204
205 if let Some(expanded) = expand_home(&path).context("error expanding ~")? {
206 path = expanded;
207 }
208
209 Ok(Some(path))
210}
211
212pub fn write_png_rgba8(
213 w: impl Write,
214 width: u32,
215 height: u32,
216 pixels: &[u8],
217) -> Result<(), png::EncodingError> {
218 let mut encoder = png::Encoder::new(w, width, height);
219 encoder.set_color(png::ColorType::Rgba);
220 encoder.set_depth(png::BitDepth::Eight);
221
222 let mut writer = encoder.write_header()?;
223 writer.write_image_data(pixels)
224}
225
226pub fn output_matches_name(output: &Output, target: &str) -> bool {
227 let name = output.user_data().get::<OutputName>().unwrap();
228 name.matches(target)
229}
230
231pub fn is_laptop_panel(connector: &str) -> bool {
232 matches!(connector.get(..4), Some("eDP-" | "LVDS" | "DSI-"))
233}
234
235pub fn with_toplevel_role<T>(
236 toplevel: &ToplevelSurface,
237 f: impl FnOnce(&mut XdgToplevelSurfaceRoleAttributes) -> T,
238) -> T {
239 with_states(toplevel.wl_surface(), |states| {
240 let mut role = states
241 .data_map
242 .get::<XdgToplevelSurfaceData>()
243 .unwrap()
244 .lock()
245 .unwrap();
246
247 f(&mut role)
248 })
249}
250
251pub fn get_credentials_for_surface(surface: &WlSurface) -> Option<Credentials> {
252 let handle = surface.handle().upgrade()?;
253 let dh = DisplayHandle::from(handle);
254
255 let client = dh.get_client(surface.id()).ok()?;
256 let data = client.get_data::<ClientState>().unwrap();
257 if data.credentials_unknown {
258 return None;
259 }
260
261 client.get_credentials(&dh).ok()
262}
263
264#[cfg(feature = "dbus")]
265pub fn show_screenshot_notification(image_path: Option<PathBuf>) {
266 let mut notification = notify_rust::Notification::new();
267 notification
268 .summary("Screenshot captured")
269 .body("You can paste the image from the clipboard.")
270 .urgency(notify_rust::Urgency::Normal)
271 .hint(notify_rust::Hint::Transient(true));
272
273 // Try to add the screenshot as an image if possible.
274 if let Some(path) = image_path {
275 match path.canonicalize() {
276 Ok(path) => match url::Url::from_file_path(path) {
277 Ok(url) => {
278 notification.image_path(url.as_str());
279 }
280 Err(err) => {
281 warn!("error converting screenshot path to file url: {err:?}");
282 }
283 },
284 Err(err) => {
285 warn!("error canonicalizing screenshot path: {err:?}");
286 }
287 }
288 }
289
290 if let Err(err) = notification.show() {
291 warn!("error showing screenshot notification: {err:?}");
292 }
293}
294
295#[inline(never)]
296pub fn cause_panic() {
297 let a = Duration::from_secs(1);
298 let b = Duration::from_secs(2);
299 let _ = a - b;
300}