forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

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