BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / notify / platform / x11_input.rs

x11_input.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
x11_input.rs 9.3 KiB Download Raw
1use std::sync::OnceLock;
2
3use gpui_kit::Window;
4use raw_window_handle::{HasWindowHandle, RawWindowHandle};
5use x11rb::connection::Connection as _;
6use x11rb::protocol::shape::{ConnectionExt as _, SK, SO};
7use x11rb::protocol::xproto::{AtomEnum, ClipOrdering, ConnectionExt as _, PropMode};
8use x11rb::rust_connection::RustConnection;
9use x11rb::wrapper::ConnectionExt as _;
10
11const WINDOW_ICON_SIZES: [u32; 3] = [32, 64, 128];
12
13fn x11_window_id(window: &Window) -> Option<u32> {
14 match HasWindowHandle::window_handle(window).ok()?.as_raw() {
15 RawWindowHandle::Xcb(handle) => Some(handle.window.get()),
16 RawWindowHandle::Xlib(handle) => u32::try_from(handle.window).ok(),
17 _ => None,
18 }
19}
20
21pub fn empty_input_region(
22 display: Option<&str>,
23 window: u32,
24) -> Result<(), Box<dyn std::error::Error>> {
25 let (connection, _) = RustConnection::connect(display)?;
26 connection
27 .shape_rectangles(
28 SO::SET,
29 SK::INPUT,
30 ClipOrdering::UNSORTED,
31 window,
32 0,
33 0,
34 &[],
35 )?
36 .check()?;
37 Ok(())
38}
39
40pub fn make_input_transparent(window: &Window) {
41 if let Some(id) = x11_window_id(window) {
42 let _ = empty_input_region(None, id);
43 }
44}
45
46pub fn compositor_running(display: Option<&str>) -> Result<bool, Box<dyn std::error::Error>> {
47 let (connection, screen_number) = RustConnection::connect(display)?;
48 let selection = format!("_NET_WM_CM_S{screen_number}");
49 let atom = connection
50 .intern_atom(false, selection.as_bytes())?
51 .reply()?
52 .atom;
53 let owner = connection.get_selection_owner(atom)?.reply()?.owner;
54 Ok(owner != x11rb::NONE)
55}
56
57pub fn window_transparency_available(window: &Window) -> bool {
58 static COMPOSITED: OnceLock<bool> = OnceLock::new();
59 match HasWindowHandle::window_handle(window).map(|handle| handle.as_raw()) {
60 Ok(RawWindowHandle::Xcb(_) | RawWindowHandle::Xlib(_)) => {
61 *COMPOSITED.get_or_init(|| compositor_running(None).unwrap_or(false))
62 }
63 _ => true,
64 }
65}
66
67pub fn window_icon_property(png: &[u8]) -> Option<Vec<u32>> {
68 let decoded = image::load_from_memory(png).ok()?;
69 let mut property = Vec::new();
70 for size in WINDOW_ICON_SIZES {
71 let resized = decoded
72 .resize_exact(size, size, image::imageops::FilterType::Lanczos3)
73 .to_rgba8();
74 property.extend([size, size]);
75 property.extend(resized.pixels().map(|pixel| {
76 let [red, green, blue, alpha] = pixel.0;
77 u32::from_le_bytes([blue, green, red, alpha])
78 }));
79 }
80 Some(property)
81}
82
83pub fn write_window_icon(
84 display: Option<&str>,
85 window: u32,
86 property: &[u32],
87) -> Result<(), Box<dyn std::error::Error>> {
88 let (connection, _) = RustConnection::connect(display)?;
89 let atom = connection
90 .intern_atom(false, b"_NET_WM_ICON")?
91 .reply()?
92 .atom;
93 connection
94 .change_property32(
95 PropMode::REPLACE,
96 window,
97 atom,
98 AtomEnum::CARDINAL,
99 property,
100 )?
101 .check()?;
102 connection.flush()?;
103 Ok(())
104}
105
106pub fn set_window_icon(window: &Window, png: &[u8]) {
107 if let (Some(id), Some(property)) = (x11_window_id(window), window_icon_property(png)) {
108 let _ = write_window_icon(None, id, &property);
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use std::io::{BufRead, BufReader};
115 use std::process::{Child, Command, Stdio};
116 use std::sync::mpsc;
117 use std::time::Duration;
118
119 use x11rb::COPY_DEPTH_FROM_PARENT;
120 use x11rb::connection::Connection;
121 use x11rb::protocol::xproto::{CreateWindowAux, WindowClass};
122
123 use super::*;
124
125 const SERVER_START_TIMEOUT: Duration = Duration::from_secs(5);
126
127 struct Server(Child);
128
129 impl Drop for Server {
130 fn drop(&mut self) {
131 // SIGKILL leaves /tmp/.X<n>-lock behind, and the next run then cannot claim that display.
132 let _ = Command::new("kill").arg(self.0.id().to_string()).status();
133 let _ = self.0.wait();
134 }
135 }
136
137 fn start_server() -> Option<(Server, String)> {
138 let mut child = Command::new("Xvfb")
139 .args([
140 "-displayfd",
141 "1",
142 "-screen",
143 "0",
144 "320x200x24",
145 "-nolisten",
146 "tcp",
147 "-noreset",
148 ])
149 .stdout(Stdio::piped())
150 .stderr(Stdio::null())
151 .spawn()
152 .ok()?;
153 let stdout = child.stdout.take()?;
154 let server = Server(child);
155 let (sender, receiver) = mpsc::channel();
156 std::thread::spawn(move || {
157 let mut number = String::new();
158 let _ = BufReader::new(stdout).read_line(&mut number);
159 let _ = sender.send(number);
160 });
161 let number = receiver.recv_timeout(SERVER_START_TIMEOUT).ok()?;
162 let display = format!(":{}", number.trim());
163 RustConnection::connect(Some(&display)).ok()?;
164 Some((server, display))
165 }
166
167 #[test]
168 fn the_border_window_gets_an_empty_input_region() {
169 let Some((_server, display)) = start_server() else {
170 return;
171 };
172 let (connection, screen_number) = RustConnection::connect(Some(&display)).unwrap();
173 let root = connection.setup().roots[screen_number].root;
174 let window = connection.generate_id().unwrap();
175 connection
176 .create_window(
177 COPY_DEPTH_FROM_PARENT,
178 window,
179 root,
180 0,
181 0,
182 100,
183 100,
184 0,
185 WindowClass::INPUT_OUTPUT,
186 0,
187 &CreateWindowAux::new(),
188 )
189 .unwrap();
190 connection.flush().unwrap();
191 let before = connection
192 .shape_get_rectangles(window, SK::INPUT)
193 .unwrap()
194 .reply()
195 .unwrap();
196 assert_eq!(before.rectangles.len(), 1);
197 empty_input_region(Some(&display), window).unwrap();
198 let after = connection
199 .shape_get_rectangles(window, SK::INPUT)
200 .unwrap()
201 .reply()
202 .unwrap();
203 assert!(after.rectangles.is_empty());
204 }
205
206 #[test]
207 fn transparency_needs_a_compositor_owning_the_cm_selection() {
208 let Some((_server, display)) = start_server() else {
209 return;
210 };
211 assert!(!compositor_running(Some(&display)).unwrap());
212 let (connection, screen_number) = RustConnection::connect(Some(&display)).unwrap();
213 let root = connection.setup().roots[screen_number].root;
214 let window = connection.generate_id().unwrap();
215 connection
216 .create_window(
217 COPY_DEPTH_FROM_PARENT,
218 window,
219 root,
220 0,
221 0,
222 1,
223 1,
224 0,
225 WindowClass::INPUT_OUTPUT,
226 0,
227 &CreateWindowAux::new(),
228 )
229 .unwrap();
230 let selection = format!("_NET_WM_CM_S{screen_number}");
231 let atom = connection
232 .intern_atom(false, selection.as_bytes())
233 .unwrap()
234 .reply()
235 .unwrap()
236 .atom;
237 connection
238 .set_selection_owner(window, atom, x11rb::CURRENT_TIME)
239 .unwrap()
240 .check()
241 .unwrap();
242 assert!(compositor_running(Some(&display)).unwrap());
243 }
244
245 #[test]
246 fn the_window_icon_property_holds_every_size_in_argb() {
247 let png = crate::appearance::AppIcon::MicrosoftTeams.png();
248 let property = window_icon_property(png).unwrap();
249 let expected: usize = WINDOW_ICON_SIZES
250 .iter()
251 .map(|size| 2 + (size * size) as usize)
252 .sum();
253 assert_eq!(property.len(), expected);
254 assert_eq!(&property[..2], &[32, 32]);
255 assert!(window_icon_property(b"not a png").is_none());
256 }
257
258 #[test]
259 fn the_window_icon_lands_in_net_wm_icon() {
260 let Some((_server, display)) = start_server() else {
261 return;
262 };
263 let (connection, screen_number) = RustConnection::connect(Some(&display)).unwrap();
264 let root = connection.setup().roots[screen_number].root;
265 let window = connection.generate_id().unwrap();
266 connection
267 .create_window(
268 COPY_DEPTH_FROM_PARENT,
269 window,
270 root,
271 0,
272 0,
273 100,
274 100,
275 0,
276 WindowClass::INPUT_OUTPUT,
277 0,
278 &CreateWindowAux::new(),
279 )
280 .unwrap();
281 connection.flush().unwrap();
282 let property = window_icon_property(crate::appearance::AppIcon::RustyTeams.png()).unwrap();
283 write_window_icon(Some(&display), window, &property).unwrap();
284 let atom = connection
285 .intern_atom(false, b"_NET_WM_ICON")
286 .unwrap()
287 .reply()
288 .unwrap()
289 .atom;
290 let reply = connection
291 .get_property(false, window, atom, AtomEnum::CARDINAL, 0, u32::MAX)
292 .unwrap()
293 .reply()
294 .unwrap();
295 let stored: Vec<u32> = reply.value32().unwrap().collect();
296 assert_eq!(stored, property);
297 }
298}