1use std::cell::RefCell;
2use std::collections::HashSet;
3use std::ops::Deref;
4use std::path::PathBuf;
5use std::rc::{Rc, Weak};
6use std::time::{Duration, Instant};
7
8use calloop::generic::{FdWrapper, Generic};
9use calloop::{EventLoop, LoopHandle, RegistrationToken};
10
11use collections::HashMap;
12use util::ResultExt;
13
14use x11rb::connection::{Connection, RequestConnection};
15use x11rb::cursor;
16use x11rb::errors::ConnectionError;
17use x11rb::protocol::randr::ConnectionExt as _;
18use x11rb::protocol::xinput::ConnectionExt;
19use x11rb::protocol::xkb::ConnectionExt as _;
20use x11rb::protocol::xproto::{ChangeWindowAttributesAux, ConnectionExt as _, KeyPressEvent};
21use x11rb::protocol::{randr, render, xinput, xkb, xproto, Event};
22use x11rb::resource_manager::Database;
23use x11rb::xcb_ffi::XCBConnection;
24use xim::{x11rb::X11rbClient, Client};
25use xim::{AttributeName, InputStyle};
26use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
27use xkbcommon::xkb::{self as xkbc, LayoutIndex, ModMask};
28
29use crate::platform::linux::LinuxClient;
30use crate::platform::{LinuxCommon, PlatformWindow};
31use crate::{
32 modifiers_from_xinput_info, point, px, AnyWindowHandle, Bounds, ClipboardItem, CursorStyle,
33 DisplayId, Keystroke, Modifiers, ModifiersChangedEvent, Pixels, Platform, PlatformDisplay,
34 PlatformInput, Point, ScrollDelta, Size, TouchPhase, WindowParams, X11Window,
35};
36
37use super::{button_of_key, modifiers_from_state, pressed_button_from_mask};
38use super::{X11Display, X11WindowStatePtr, XcbAtoms};
39use super::{XimCallbackEvent, XimHandler};
40use crate::platform::linux::platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES};
41use crate::platform::linux::xdg_desktop_portal::{Event as XDPEvent, XDPEventSource};
42use crate::platform::linux::{
43 get_xkb_compose_state, is_within_click_distance, open_uri_internal, reveal_path_internal,
44};
45
46pub(super) const XINPUT_MASTER_DEVICE: u16 = 1;
47
48pub(crate) struct WindowRef {
49 window: X11WindowStatePtr,
50 refresh_event_token: RegistrationToken,
51}
52
53impl WindowRef {
54 pub fn handle(&self) -> AnyWindowHandle {
55 self.window.state.borrow().handle
56 }
57}
58
59impl Deref for WindowRef {
60 type Target = X11WindowStatePtr;
61
62 fn deref(&self) -> &Self::Target {
63 &self.window
64 }
65}
66
67#[derive(Debug)]
68#[non_exhaustive]
69pub enum EventHandlerError {
70 XCBConnectionError(ConnectionError),
71 XIMClientError(xim::ClientError),
72}
73
74impl std::error::Error for EventHandlerError {}
75
76impl std::fmt::Display for EventHandlerError {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 match self {
79 EventHandlerError::XCBConnectionError(err) => err.fmt(f),
80 EventHandlerError::XIMClientError(err) => err.fmt(f),
81 }
82 }
83}
84
85impl From<ConnectionError> for EventHandlerError {
86 fn from(err: ConnectionError) -> Self {
87 EventHandlerError::XCBConnectionError(err)
88 }
89}
90
91impl From<xim::ClientError> for EventHandlerError {
92 fn from(err: xim::ClientError) -> Self {
93 EventHandlerError::XIMClientError(err)
94 }
95}
96
97#[derive(Debug, Default, Clone)]
98struct XKBStateNotiy {
99 depressed_layout: LayoutIndex,
100 latched_layout: LayoutIndex,
101 locked_layout: LayoutIndex,
102}
103
104pub struct X11ClientState {
105 pub(crate) loop_handle: LoopHandle<'static, X11Client>,
106 pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
107
108 pub(crate) last_click: Instant,
109 pub(crate) last_location: Point<Pixels>,
110 pub(crate) current_count: usize,
111
112 pub(crate) scale_factor: f32,
113
114 xkb_context: xkbc::Context,
115 pub(crate) xcb_connection: Rc<XCBConnection>,
116 xkb_device_id: i32,
117 client_side_decorations_supported: bool,
118 pub(crate) x_root_index: usize,
119 pub(crate) _resource_database: Database,
120 pub(crate) atoms: XcbAtoms,
121 pub(crate) windows: HashMap<xproto::Window, WindowRef>,
122 pub(crate) mouse_focused_window: Option<xproto::Window>,
123 pub(crate) keyboard_focused_window: Option<xproto::Window>,
124 pub(crate) xkb: xkbc::State,
125 previous_xkb_state: XKBStateNotiy,
126 pub(crate) ximc: Option<X11rbClient<Rc<XCBConnection>>>,
127 pub(crate) xim_handler: Option<XimHandler>,
128 pub modifiers: Modifiers,
129
130 pub(crate) compose_state: Option<xkbc::compose::State>,
131 pub(crate) pre_edit_text: Option<String>,
132 pub(crate) composing: bool,
133 pub(crate) pre_ime_key_down: Option<Keystroke>,
134 pub(crate) cursor_handle: cursor::Handle,
135 pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
136 pub(crate) cursor_cache: HashMap<CursorStyle, xproto::Cursor>,
137
138 pub(crate) scroll_class_data: Vec<xinput::DeviceClassDataScroll>,
139 pub(crate) scroll_x: Option<f32>,
140 pub(crate) scroll_y: Option<f32>,
141
142 pub(crate) common: LinuxCommon,
143 pub(crate) clipboard: x11_clipboard::Clipboard,
144 pub(crate) clipboard_item: Option<ClipboardItem>,
145}
146
147#[derive(Clone)]
148pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
149
150impl X11ClientStatePtr {
151 pub fn drop_window(&self, x_window: u32) {
152 let client = X11Client(self.0.upgrade().expect("client already dropped"));
153 let mut state = client.0.borrow_mut();
154
155 if let Some(window_ref) = state.windows.remove(&x_window) {
156 state.loop_handle.remove(window_ref.refresh_event_token);
157 }
158 if state.mouse_focused_window == Some(x_window) {
159 state.mouse_focused_window = None;
160 }
161 if state.keyboard_focused_window == Some(x_window) {
162 state.keyboard_focused_window = None;
163 }
164 state.cursor_styles.remove(&x_window);
165
166 if state.windows.is_empty() {
167 state.common.signal.stop();
168 }
169 }
170}
171
172#[derive(Clone)]
173pub(crate) struct X11Client(Rc<RefCell<X11ClientState>>);
174
175impl X11Client {
176 pub(crate) fn new() -> Self {
177 let event_loop = EventLoop::try_new().unwrap();
178
179 let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
180
181 let handle = event_loop.handle();
182
183 handle
184 .insert_source(main_receiver, {
185 let handle = handle.clone();
186 move |event, _, _: &mut X11Client| {
187 if let calloop::channel::Event::Msg(runnable) = event {
188 // Insert the runnables as idle callbacks, so we make sure that user-input and X11
189 // events have higher priority and runnables are only worked off after the event
190 // callbacks.
191 handle.insert_idle(|_| {
192 runnable.run();
193 });
194 }
195 }
196 })
197 .unwrap();
198
199 let (xcb_connection, x_root_index) = XCBConnection::connect(None).unwrap();
200 xcb_connection
201 .prefetch_extension_information(xkb::X11_EXTENSION_NAME)
202 .unwrap();
203 xcb_connection
204 .prefetch_extension_information(randr::X11_EXTENSION_NAME)
205 .unwrap();
206 xcb_connection
207 .prefetch_extension_information(render::X11_EXTENSION_NAME)
208 .unwrap();
209 xcb_connection
210 .prefetch_extension_information(xinput::X11_EXTENSION_NAME)
211 .unwrap();
212
213 let xinput_version = xcb_connection
214 .xinput_xi_query_version(2, 0)
215 .unwrap()
216 .reply()
217 .unwrap();
218 assert!(
219 xinput_version.major_version >= 2,
220 "XInput Extension v2 not supported."
221 );
222
223 let master_device_query = xcb_connection
224 .xinput_xi_query_device(XINPUT_MASTER_DEVICE)
225 .unwrap()
226 .reply()
227 .unwrap();
228 let scroll_class_data = master_device_query
229 .infos
230 .iter()
231 .find(|info| info.type_ == xinput::DeviceType::MASTER_POINTER)
232 .unwrap()
233 .classes
234 .iter()
235 .filter_map(|class| class.data.as_scroll())
236 .map(|class| *class)
237 .collect::<Vec<_>>();
238
239 let atoms = XcbAtoms::new(&xcb_connection).unwrap().reply().unwrap();
240
241 let root = xcb_connection.setup().roots[0].root;
242 let compositor_present = check_compositor_present(&xcb_connection, root);
243 let gtk_frame_extents_supported =
244 check_gtk_frame_extents_supported(&xcb_connection, &atoms, root);
245 let client_side_decorations_supported = compositor_present && gtk_frame_extents_supported;
246 log::info!(
247 "x11: compositor present: {}, gtk_frame_extents_supported: {}",
248 compositor_present,
249 gtk_frame_extents_supported
250 );
251
252 let xkb = xcb_connection
253 .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION)
254 .unwrap()
255 .reply()
256 .unwrap();
257
258 let events = xkb::EventType::STATE_NOTIFY
259 | xkb::EventType::MAP_NOTIFY
260 | xkb::EventType::NEW_KEYBOARD_NOTIFY;
261 xcb_connection
262 .xkb_select_events(
263 xkb::ID::USE_CORE_KBD.into(),
264 0u8.into(),
265 events,
266 0u8.into(),
267 0u8.into(),
268 &xkb::SelectEventsAux::new(),
269 )
270 .unwrap();
271 assert!(xkb.supported);
272
273 let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
274 let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
275 let xkb_state = {
276 let xkb_keymap = xkbc::x11::keymap_new_from_device(
277 &xkb_context,
278 &xcb_connection,
279 xkb_device_id,
280 xkbc::KEYMAP_COMPILE_NO_FLAGS,
281 );
282 xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
283 };
284 let compose_state = get_xkb_compose_state(&xkb_context);
285 let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection).unwrap();
286
287 let scale_factor = resource_database
288 .get_value("Xft.dpi", "Xft.dpi")
289 .ok()
290 .flatten()
291 .map(|dpi: f32| dpi / 96.0)
292 .unwrap_or(1.0);
293
294 let cursor_handle = cursor::Handle::new(&xcb_connection, x_root_index, &resource_database)
295 .unwrap()
296 .reply()
297 .unwrap();
298
299 let clipboard = x11_clipboard::Clipboard::new().unwrap();
300
301 let xcb_connection = Rc::new(xcb_connection);
302
303 let ximc = X11rbClient::init(Rc::clone(&xcb_connection), x_root_index, None).ok();
304 let xim_handler = if ximc.is_some() {
305 Some(XimHandler::new())
306 } else {
307 None
308 };
309
310 // Safety: Safe if xcb::Connection always returns a valid fd
311 let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
312
313 handle
314 .insert_source(
315 Generic::new_with_error::<EventHandlerError>(
316 fd,
317 calloop::Interest::READ,
318 calloop::Mode::Level,
319 ),
320 {
321 let xcb_connection = xcb_connection.clone();
322 move |_readiness, _, client| {
323 client.process_x11_events(&xcb_connection)?;
324 Ok(calloop::PostAction::Continue)
325 }
326 },
327 )
328 .expect("Failed to initialize x11 event source");
329
330 handle
331 .insert_source(XDPEventSource::new(&common.background_executor), {
332 move |event, _, client| match event {
333 XDPEvent::WindowAppearance(appearance) => {
334 client.with_common(|common| common.appearance = appearance);
335 for (_, window) in &mut client.0.borrow_mut().windows {
336 window.window.set_appearance(appearance);
337 }
338 }
339 XDPEvent::CursorTheme(_) | XDPEvent::CursorSize(_) => {
340 // noop, X11 manages this for us.
341 }
342 }
343 })
344 .unwrap();
345
346 X11Client(Rc::new(RefCell::new(X11ClientState {
347 modifiers: Modifiers::default(),
348 event_loop: Some(event_loop),
349 loop_handle: handle,
350 common,
351 last_click: Instant::now(),
352 last_location: Point::new(px(0.0), px(0.0)),
353 current_count: 0,
354 scale_factor,
355
356 xkb_context,
357 xcb_connection,
358 xkb_device_id,
359 client_side_decorations_supported,
360 x_root_index,
361 _resource_database: resource_database,
362 atoms,
363 windows: HashMap::default(),
364 mouse_focused_window: None,
365 keyboard_focused_window: None,
366 xkb: xkb_state,
367 previous_xkb_state: XKBStateNotiy::default(),
368 ximc,
369 xim_handler,
370
371 compose_state,
372 pre_edit_text: None,
373 pre_ime_key_down: None,
374 composing: false,
375
376 cursor_handle,
377 cursor_styles: HashMap::default(),
378 cursor_cache: HashMap::default(),
379
380 scroll_class_data,
381 scroll_x: None,
382 scroll_y: None,
383
384 clipboard,
385 clipboard_item: None,
386 })))
387 }
388
389 pub fn process_x11_events(
390 &self,
391 xcb_connection: &XCBConnection,
392 ) -> Result<(), EventHandlerError> {
393 loop {
394 let mut events = Vec::new();
395 let mut windows_to_refresh = HashSet::new();
396
397 let mut last_key_release = None;
398 let mut last_key_press: Option<KeyPressEvent> = None;
399
400 loop {
401 match xcb_connection.poll_for_event() {
402 Ok(Some(event)) => {
403 match event {
404 Event::Expose(expose_event) => {
405 windows_to_refresh.insert(expose_event.window);
406 }
407 Event::KeyRelease(_) => {
408 last_key_release = Some(event);
409 }
410 Event::KeyPress(key_press) => {
411 if let Some(last_press) = last_key_press.as_ref() {
412 if last_press.detail == key_press.detail {
413 continue;
414 }
415 }
416
417 if let Some(Event::KeyRelease(key_release)) =
418 last_key_release.take()
419 {
420 // We ignore that last KeyRelease if it's too close to this KeyPress,
421 // suggesting that it's auto-generated by X11 as a key-repeat event.
422 if key_release.detail != key_press.detail
423 || key_press.time.saturating_sub(key_release.time) > 20
424 {
425 events.push(Event::KeyRelease(key_release));
426 }
427 }
428 events.push(Event::KeyPress(key_press));
429 last_key_press = Some(key_press);
430 }
431 _ => {
432 if let Some(release_event) = last_key_release.take() {
433 events.push(release_event);
434 }
435 events.push(event);
436 }
437 }
438 }
439 Ok(None) => {
440 // Add any remaining stored KeyRelease event
441 if let Some(release_event) = last_key_release.take() {
442 events.push(release_event);
443 }
444 break;
445 }
446 Err(e) => {
447 log::warn!("error polling for X11 events: {e:?}");
448 break;
449 }
450 }
451 }
452
453 if events.is_empty() && windows_to_refresh.is_empty() {
454 break;
455 }
456
457 for window in windows_to_refresh.into_iter() {
458 if let Some(window) = self.get_window(window) {
459 window.refresh();
460 }
461 }
462
463 for event in events.into_iter() {
464 let mut state = self.0.borrow_mut();
465 if state.ximc.is_none() || state.xim_handler.is_none() {
466 drop(state);
467 self.handle_event(event);
468 continue;
469 }
470
471 let mut ximc = state.ximc.take().unwrap();
472 let mut xim_handler = state.xim_handler.take().unwrap();
473 let xim_connected = xim_handler.connected;
474 drop(state);
475
476 let xim_filtered = match ximc.filter_event(&event, &mut xim_handler) {
477 Ok(handled) => handled,
478 Err(err) => {
479 log::error!("XIMClientError: {}", err);
480 false
481 }
482 };
483 let xim_callback_event = xim_handler.last_callback_event.take();
484
485 let mut state = self.0.borrow_mut();
486 state.ximc = Some(ximc);
487 state.xim_handler = Some(xim_handler);
488 drop(state);
489
490 if let Some(event) = xim_callback_event {
491 self.handle_xim_callback_event(event);
492 }
493
494 if xim_filtered {
495 continue;
496 }
497
498 if xim_connected {
499 self.xim_handle_event(event);
500 } else {
501 self.handle_event(event);
502 }
503 }
504 }
505 Ok(())
506 }
507
508 pub fn enable_ime(&self) {
509 let mut state = self.0.borrow_mut();
510 if state.ximc.is_none() {
511 return;
512 }
513
514 let mut ximc = state.ximc.take().unwrap();
515 let mut xim_handler = state.xim_handler.take().unwrap();
516 let mut ic_attributes = ximc
517 .build_ic_attributes()
518 .push(
519 AttributeName::InputStyle,
520 InputStyle::PREEDIT_CALLBACKS
521 | InputStyle::STATUS_NOTHING
522 | InputStyle::PREEDIT_NONE,
523 )
524 .push(AttributeName::ClientWindow, xim_handler.window)
525 .push(AttributeName::FocusWindow, xim_handler.window);
526
527 let window_id = state.keyboard_focused_window;
528 drop(state);
529 if let Some(window_id) = window_id {
530 let window = self.get_window(window_id).unwrap();
531 if let Some(area) = window.get_ime_area() {
532 ic_attributes =
533 ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
534 b.push(
535 xim::AttributeName::SpotLocation,
536 xim::Point {
537 x: u32::from(area.origin.x + area.size.width) as i16,
538 y: u32::from(area.origin.y + area.size.height) as i16,
539 },
540 );
541 });
542 }
543 }
544 ximc.create_ic(xim_handler.im_id, ic_attributes.build())
545 .ok();
546 state = self.0.borrow_mut();
547 state.xim_handler = Some(xim_handler);
548 state.ximc = Some(ximc);
549 }
550
551 pub fn disable_ime(&self) {
552 let mut state = self.0.borrow_mut();
553 state.composing = false;
554 if let Some(mut ximc) = state.ximc.take() {
555 let xim_handler = state.xim_handler.as_ref().unwrap();
556 ximc.destroy_ic(xim_handler.im_id, xim_handler.ic_id).ok();
557 state.ximc = Some(ximc);
558 }
559 }
560
561 fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
562 let state = self.0.borrow();
563 state
564 .windows
565 .get(&win)
566 .filter(|window_reference| !window_reference.window.state.borrow().destroyed)
567 .map(|window_reference| window_reference.window.clone())
568 }
569
570 fn handle_event(&self, event: Event) -> Option<()> {
571 match event {
572 Event::ClientMessage(event) => {
573 let window = self.get_window(event.window)?;
574 let [atom, _arg1, arg2, arg3, _arg4] = event.data.as_data32();
575 let mut state = self.0.borrow_mut();
576
577 if atom == state.atoms.WM_DELETE_WINDOW {
578 // window "x" button clicked by user
579 if window.should_close() {
580 // Rest of the close logic is handled in drop_window()
581 window.close();
582 }
583 } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
584 window.state.borrow_mut().last_sync_counter =
585 Some(x11rb::protocol::sync::Int64 {
586 lo: arg2,
587 hi: arg3 as i32,
588 })
589 }
590 }
591 Event::ConfigureNotify(event) => {
592 let bounds = Bounds {
593 origin: Point {
594 x: event.x.into(),
595 y: event.y.into(),
596 },
597 size: Size {
598 width: event.width.into(),
599 height: event.height.into(),
600 },
601 };
602 let window = self.get_window(event.window)?;
603 window.configure(bounds);
604 }
605 Event::PropertyNotify(event) => {
606 let window = self.get_window(event.window)?;
607 window.property_notify(event);
608 }
609 Event::FocusIn(event) => {
610 let window = self.get_window(event.event)?;
611 window.set_active(true);
612 let mut state = self.0.borrow_mut();
613 state.keyboard_focused_window = Some(event.event);
614 drop(state);
615 self.enable_ime();
616 }
617 Event::FocusOut(event) => {
618 let window = self.get_window(event.event)?;
619 window.set_active(false);
620 let mut state = self.0.borrow_mut();
621 state.keyboard_focused_window = None;
622 if let Some(compose_state) = state.compose_state.as_mut() {
623 compose_state.reset();
624 }
625 state.pre_edit_text.take();
626 drop(state);
627 self.disable_ime();
628 window.handle_ime_delete();
629 }
630 Event::XkbNewKeyboardNotify(_) | Event::MapNotify(_) => {
631 let mut state = self.0.borrow_mut();
632 let xkb_state = {
633 let xkb_keymap = xkbc::x11::keymap_new_from_device(
634 &state.xkb_context,
635 &state.xcb_connection,
636 state.xkb_device_id,
637 xkbc::KEYMAP_COMPILE_NO_FLAGS,
638 );
639 xkbc::x11::state_new_from_device(
640 &xkb_keymap,
641 &state.xcb_connection,
642 state.xkb_device_id,
643 )
644 };
645 state.xkb = xkb_state;
646 }
647 Event::XkbStateNotify(event) => {
648 let mut state = self.0.borrow_mut();
649 state.xkb.update_mask(
650 event.base_mods.into(),
651 event.latched_mods.into(),
652 event.locked_mods.into(),
653 event.base_group as u32,
654 event.latched_group as u32,
655 event.locked_group.into(),
656 );
657 state.previous_xkb_state = XKBStateNotiy {
658 depressed_layout: event.base_group as u32,
659 latched_layout: event.latched_group as u32,
660 locked_layout: event.locked_group.into(),
661 };
662 let modifiers = Modifiers::from_xkb(&state.xkb);
663 if state.modifiers == modifiers {
664 drop(state);
665 } else {
666 let focused_window_id = state.keyboard_focused_window?;
667 state.modifiers = modifiers;
668 drop(state);
669
670 let focused_window = self.get_window(focused_window_id)?;
671 focused_window.handle_input(PlatformInput::ModifiersChanged(
672 ModifiersChangedEvent { modifiers },
673 ));
674 }
675 }
676 Event::KeyPress(event) => {
677 let window = self.get_window(event.event)?;
678 let mut state = self.0.borrow_mut();
679
680 let modifiers = modifiers_from_state(event.state);
681 state.modifiers = modifiers;
682 state.pre_ime_key_down.take();
683 let keystroke = {
684 let code = event.detail.into();
685 let xkb_state = state.previous_xkb_state.clone();
686 state.xkb.update_mask(
687 event.state.bits() as ModMask,
688 0,
689 0,
690 xkb_state.depressed_layout,
691 xkb_state.latched_layout,
692 xkb_state.locked_layout,
693 );
694 let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
695 let keysym = state.xkb.key_get_one_sym(code);
696 if keysym.is_modifier_key() {
697 return Some(());
698 }
699 if let Some(mut compose_state) = state.compose_state.take() {
700 compose_state.feed(keysym);
701 match compose_state.status() {
702 xkbc::Status::Composed => {
703 state.pre_edit_text.take();
704 keystroke.ime_key = compose_state.utf8();
705 if let Some(keysym) = compose_state.keysym() {
706 keystroke.key = xkbc::keysym_get_name(keysym);
707 }
708 }
709 xkbc::Status::Composing => {
710 keystroke.ime_key = None;
711 state.pre_edit_text = compose_state
712 .utf8()
713 .or(crate::Keystroke::underlying_dead_key(keysym));
714 let pre_edit =
715 state.pre_edit_text.clone().unwrap_or(String::default());
716 drop(state);
717 window.handle_ime_preedit(pre_edit);
718 state = self.0.borrow_mut();
719 }
720 xkbc::Status::Cancelled => {
721 let pre_edit = state.pre_edit_text.take();
722 drop(state);
723 if let Some(pre_edit) = pre_edit {
724 window.handle_ime_commit(pre_edit);
725 }
726 if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
727 window.handle_ime_preedit(current_key);
728 }
729 state = self.0.borrow_mut();
730 compose_state.feed(keysym);
731 }
732 _ => {}
733 }
734 state.compose_state = Some(compose_state);
735 }
736 keystroke
737 };
738 drop(state);
739 window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
740 keystroke,
741 is_held: false,
742 }));
743 }
744 Event::KeyRelease(event) => {
745 let window = self.get_window(event.event)?;
746 let mut state = self.0.borrow_mut();
747
748 let modifiers = modifiers_from_state(event.state);
749 state.modifiers = modifiers;
750
751 let keystroke = {
752 let code = event.detail.into();
753 let xkb_state = state.previous_xkb_state.clone();
754 state.xkb.update_mask(
755 event.state.bits() as ModMask,
756 0,
757 0,
758 xkb_state.depressed_layout,
759 xkb_state.latched_layout,
760 xkb_state.locked_layout,
761 );
762 let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
763 let keysym = state.xkb.key_get_one_sym(code);
764 if keysym.is_modifier_key() {
765 return Some(());
766 }
767 keystroke
768 };
769 drop(state);
770 window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
771 }
772 Event::XinputButtonPress(event) => {
773 let window = self.get_window(event.event)?;
774 let mut state = self.0.borrow_mut();
775
776 let modifiers = modifiers_from_xinput_info(event.mods);
777 state.modifiers = modifiers;
778
779 let position = point(
780 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
781 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
782 );
783
784 if state.composing && state.ximc.is_some() {
785 drop(state);
786 self.disable_ime();
787 self.enable_ime();
788 window.handle_ime_unmark();
789 state = self.0.borrow_mut();
790 } else if let Some(text) = state.pre_edit_text.take() {
791 if let Some(compose_state) = state.compose_state.as_mut() {
792 compose_state.reset();
793 }
794 drop(state);
795 window.handle_ime_commit(text);
796 state = self.0.borrow_mut();
797 }
798 if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
799 let click_elapsed = state.last_click.elapsed();
800
801 if click_elapsed < DOUBLE_CLICK_INTERVAL
802 && is_within_click_distance(state.last_location, position)
803 {
804 state.current_count += 1;
805 } else {
806 state.current_count = 1;
807 }
808
809 state.last_click = Instant::now();
810 state.last_location = position;
811 let current_count = state.current_count;
812
813 drop(state);
814 window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
815 button,
816 position,
817 modifiers,
818 click_count: current_count,
819 first_mouse: false,
820 }));
821 } else {
822 log::warn!("Unknown button press: {event:?}");
823 }
824 }
825 Event::XinputButtonRelease(event) => {
826 let window = self.get_window(event.event)?;
827 let mut state = self.0.borrow_mut();
828 let modifiers = modifiers_from_xinput_info(event.mods);
829 state.modifiers = modifiers;
830
831 let position = point(
832 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
833 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
834 );
835 if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
836 let click_count = state.current_count;
837 drop(state);
838 window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
839 button,
840 position,
841 modifiers,
842 click_count,
843 }));
844 }
845 }
846 Event::XinputMotion(event) => {
847 let window = self.get_window(event.event)?;
848 let mut state = self.0.borrow_mut();
849 let pressed_button = pressed_button_from_mask(event.button_mask[0]);
850 let position = point(
851 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
852 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
853 );
854 let modifiers = modifiers_from_xinput_info(event.mods);
855 state.modifiers = modifiers;
856 drop(state);
857
858 let axisvalues = event
859 .axisvalues
860 .iter()
861 .map(|axisvalue| fp3232_to_f32(*axisvalue))
862 .collect::<Vec<_>>();
863
864 if event.valuator_mask[0] & 3 != 0 {
865 window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
866 position,
867 pressed_button,
868 modifiers,
869 }));
870 }
871
872 let mut valuator_idx = 0;
873 let scroll_class_data = self.0.borrow().scroll_class_data.clone();
874 for shift in 0..32 {
875 if (event.valuator_mask[0] >> shift) & 1 == 0 {
876 continue;
877 }
878
879 for scroll_class in &scroll_class_data {
880 if scroll_class.scroll_type == xinput::ScrollType::HORIZONTAL
881 && scroll_class.number == shift
882 {
883 let new_scroll = axisvalues[valuator_idx]
884 / fp3232_to_f32(scroll_class.increment)
885 * SCROLL_LINES as f32;
886 let old_scroll = self.0.borrow().scroll_x;
887 self.0.borrow_mut().scroll_x = Some(new_scroll);
888
889 if let Some(old_scroll) = old_scroll {
890 let delta_scroll = old_scroll - new_scroll;
891 window.handle_input(PlatformInput::ScrollWheel(
892 crate::ScrollWheelEvent {
893 position,
894 delta: ScrollDelta::Lines(Point::new(delta_scroll, 0.0)),
895 modifiers,
896 touch_phase: TouchPhase::default(),
897 },
898 ));
899 }
900 } else if scroll_class.scroll_type == xinput::ScrollType::VERTICAL
901 && scroll_class.number == shift
902 {
903 // the `increment` is the valuator delta equivalent to one positive unit of scrolling. Here that means SCROLL_LINES lines.
904 let new_scroll = axisvalues[valuator_idx]
905 / fp3232_to_f32(scroll_class.increment)
906 * SCROLL_LINES as f32;
907 let old_scroll = self.0.borrow().scroll_y;
908 self.0.borrow_mut().scroll_y = Some(new_scroll);
909
910 if let Some(old_scroll) = old_scroll {
911 let delta_scroll = old_scroll - new_scroll;
912 let (x, y) = if !modifiers.shift {
913 (0.0, delta_scroll)
914 } else {
915 (delta_scroll, 0.0)
916 };
917 window.handle_input(PlatformInput::ScrollWheel(
918 crate::ScrollWheelEvent {
919 position,
920 delta: ScrollDelta::Lines(Point::new(x, y)),
921 modifiers,
922 touch_phase: TouchPhase::default(),
923 },
924 ));
925 }
926 }
927 }
928
929 valuator_idx += 1;
930 }
931 }
932 Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
933 let window = self.get_window(event.event)?;
934 window.set_hovered(true);
935 let mut state = self.0.borrow_mut();
936 state.mouse_focused_window = Some(event.event);
937 }
938 Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
939 self.0.borrow_mut().scroll_x = None; // Set last scroll to `None` so that a large delta isn't created if scrolling is done outside the window (the valuator is global)
940 self.0.borrow_mut().scroll_y = None;
941
942 let mut state = self.0.borrow_mut();
943 state.mouse_focused_window = None;
944 let pressed_button = pressed_button_from_mask(event.buttons[0]);
945 let position = point(
946 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
947 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
948 );
949 let modifiers = modifiers_from_xinput_info(event.mods);
950 state.modifiers = modifiers;
951 drop(state);
952
953 let window = self.get_window(event.event)?;
954 window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
955 pressed_button,
956 position,
957 modifiers,
958 }));
959 window.set_hovered(false);
960 }
961 _ => {}
962 };
963
964 Some(())
965 }
966
967 fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
968 match event {
969 XimCallbackEvent::XimXEvent(event) => {
970 self.handle_event(event);
971 }
972 XimCallbackEvent::XimCommitEvent(window, text) => {
973 self.xim_handle_commit(window, text);
974 }
975 XimCallbackEvent::XimPreeditEvent(window, text) => {
976 self.xim_handle_preedit(window, text);
977 }
978 };
979 }
980
981 fn xim_handle_event(&self, event: Event) -> Option<()> {
982 match event {
983 Event::KeyPress(event) | Event::KeyRelease(event) => {
984 let mut state = self.0.borrow_mut();
985 state.pre_ime_key_down = Some(Keystroke::from_xkb(
986 &state.xkb,
987 state.modifiers,
988 event.detail.into(),
989 ));
990 let mut ximc = state.ximc.take().unwrap();
991 let mut xim_handler = state.xim_handler.take().unwrap();
992 drop(state);
993 xim_handler.window = event.event;
994 ximc.forward_event(
995 xim_handler.im_id,
996 xim_handler.ic_id,
997 xim::ForwardEventFlag::empty(),
998 &event,
999 )
1000 .unwrap();
1001 let mut state = self.0.borrow_mut();
1002 state.ximc = Some(ximc);
1003 state.xim_handler = Some(xim_handler);
1004 drop(state);
1005 }
1006 event => {
1007 self.handle_event(event);
1008 }
1009 }
1010 Some(())
1011 }
1012
1013 fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1014 let window = self.get_window(window).unwrap();
1015 let mut state = self.0.borrow_mut();
1016 let keystroke = state.pre_ime_key_down.take();
1017 state.composing = false;
1018 drop(state);
1019 if let Some(mut keystroke) = keystroke {
1020 keystroke.ime_key = Some(text.clone());
1021 window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1022 keystroke,
1023 is_held: false,
1024 }));
1025 }
1026
1027 Some(())
1028 }
1029
1030 fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1031 let window = self.get_window(window).unwrap();
1032 window.handle_ime_preedit(text);
1033
1034 let mut state = self.0.borrow_mut();
1035 let mut ximc = state.ximc.take().unwrap();
1036 let mut xim_handler = state.xim_handler.take().unwrap();
1037 state.composing = true;
1038 drop(state);
1039
1040 if let Some(area) = window.get_ime_area() {
1041 let ic_attributes = ximc
1042 .build_ic_attributes()
1043 .push(
1044 xim::AttributeName::InputStyle,
1045 xim::InputStyle::PREEDIT_CALLBACKS
1046 | xim::InputStyle::STATUS_NOTHING
1047 | xim::InputStyle::PREEDIT_POSITION,
1048 )
1049 .push(xim::AttributeName::ClientWindow, xim_handler.window)
1050 .push(xim::AttributeName::FocusWindow, xim_handler.window)
1051 .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1052 b.push(
1053 xim::AttributeName::SpotLocation,
1054 xim::Point {
1055 x: u32::from(area.origin.x + area.size.width) as i16,
1056 y: u32::from(area.origin.y + area.size.height) as i16,
1057 },
1058 );
1059 })
1060 .build();
1061 ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1062 .ok();
1063 }
1064 let mut state = self.0.borrow_mut();
1065 state.ximc = Some(ximc);
1066 state.xim_handler = Some(xim_handler);
1067 drop(state);
1068 Some(())
1069 }
1070}
1071
1072impl LinuxClient for X11Client {
1073 fn compositor_name(&self) -> &'static str {
1074 "X11"
1075 }
1076
1077 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1078 f(&mut self.0.borrow_mut().common)
1079 }
1080
1081 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1082 let state = self.0.borrow();
1083 let setup = state.xcb_connection.setup();
1084 setup
1085 .roots
1086 .iter()
1087 .enumerate()
1088 .filter_map(|(root_id, _)| {
1089 Some(Rc::new(X11Display::new(
1090 &state.xcb_connection,
1091 state.scale_factor,
1092 root_id,
1093 )?) as Rc<dyn PlatformDisplay>)
1094 })
1095 .collect()
1096 }
1097
1098 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1099 let state = self.0.borrow();
1100
1101 Some(Rc::new(
1102 X11Display::new(
1103 &state.xcb_connection,
1104 state.scale_factor,
1105 state.x_root_index,
1106 )
1107 .expect("There should always be a root index"),
1108 ))
1109 }
1110
1111 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1112 let state = self.0.borrow();
1113
1114 Some(Rc::new(X11Display::new(
1115 &state.xcb_connection,
1116 state.scale_factor,
1117 id.0 as usize,
1118 )?))
1119 }
1120
1121 fn open_window(
1122 &self,
1123 handle: AnyWindowHandle,
1124 params: WindowParams,
1125 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1126 let mut state = self.0.borrow_mut();
1127 let x_window = state.xcb_connection.generate_id().unwrap();
1128
1129 let window = X11Window::new(
1130 handle,
1131 X11ClientStatePtr(Rc::downgrade(&self.0)),
1132 state.common.foreground_executor.clone(),
1133 params,
1134 &state.xcb_connection,
1135 state.client_side_decorations_supported,
1136 state.x_root_index,
1137 x_window,
1138 &state.atoms,
1139 state.scale_factor,
1140 state.common.appearance,
1141 )?;
1142
1143 let screen_resources = state
1144 .xcb_connection
1145 .randr_get_screen_resources(x_window)
1146 .unwrap()
1147 .reply()
1148 .expect("Could not find available screens");
1149
1150 let mode = screen_resources
1151 .crtcs
1152 .iter()
1153 .find_map(|crtc| {
1154 let crtc_info = state
1155 .xcb_connection
1156 .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1157 .ok()?
1158 .reply()
1159 .ok()?;
1160
1161 screen_resources
1162 .modes
1163 .iter()
1164 .find(|m| m.id == crtc_info.mode)
1165 })
1166 .expect("Unable to find screen refresh rate");
1167
1168 let refresh_event_token = state
1169 .loop_handle
1170 .insert_source(calloop::timer::Timer::immediate(), {
1171 let refresh_duration = mode_refresh_rate(mode);
1172 move |mut instant, (), client| {
1173 let xcb_connection = {
1174 let state = client.0.borrow_mut();
1175 let xcb_connection = state.xcb_connection.clone();
1176 if let Some(window) = state.windows.get(&x_window) {
1177 let window = window.window.clone();
1178 drop(state);
1179 window.refresh();
1180 }
1181 xcb_connection
1182 };
1183 client.process_x11_events(&xcb_connection).log_err();
1184
1185 // Take into account that some frames have been skipped
1186 let now = Instant::now();
1187 while instant < now {
1188 instant += refresh_duration;
1189 }
1190 calloop::timer::TimeoutAction::ToInstant(instant)
1191 }
1192 })
1193 .expect("Failed to initialize refresh timer");
1194
1195 let window_ref = WindowRef {
1196 window: window.0.clone(),
1197 refresh_event_token,
1198 };
1199
1200 state.windows.insert(x_window, window_ref);
1201 Ok(Box::new(window))
1202 }
1203
1204 fn set_cursor_style(&self, style: CursorStyle) {
1205 let mut state = self.0.borrow_mut();
1206 let Some(focused_window) = state.mouse_focused_window else {
1207 return;
1208 };
1209 let current_style = state
1210 .cursor_styles
1211 .get(&focused_window)
1212 .unwrap_or(&CursorStyle::Arrow);
1213 if *current_style == style {
1214 return;
1215 }
1216
1217 let cursor = match state.cursor_cache.get(&style) {
1218 Some(cursor) => *cursor,
1219 None => {
1220 let Some(cursor) = state
1221 .cursor_handle
1222 .load_cursor(&state.xcb_connection, &style.to_icon_name())
1223 .log_err()
1224 else {
1225 return;
1226 };
1227 state.cursor_cache.insert(style, cursor);
1228 cursor
1229 }
1230 };
1231
1232 state.cursor_styles.insert(focused_window, style);
1233 state
1234 .xcb_connection
1235 .change_window_attributes(
1236 focused_window,
1237 &ChangeWindowAttributesAux {
1238 cursor: Some(cursor),
1239 ..Default::default()
1240 },
1241 )
1242 .expect("failed to change window cursor")
1243 .check()
1244 .unwrap();
1245 }
1246
1247 fn open_uri(&self, uri: &str) {
1248 open_uri_internal(self.background_executor(), uri, None);
1249 }
1250
1251 fn reveal_path(&self, path: PathBuf) {
1252 reveal_path_internal(self.background_executor(), path, None);
1253 }
1254
1255 fn write_to_primary(&self, item: crate::ClipboardItem) {
1256 let state = self.0.borrow_mut();
1257 state
1258 .clipboard
1259 .store(
1260 state.clipboard.setter.atoms.primary,
1261 state.clipboard.setter.atoms.utf8_string,
1262 item.text().unwrap_or_default().as_bytes(),
1263 )
1264 .ok();
1265 }
1266
1267 fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1268 let mut state = self.0.borrow_mut();
1269 state
1270 .clipboard
1271 .store(
1272 state.clipboard.setter.atoms.clipboard,
1273 state.clipboard.setter.atoms.utf8_string,
1274 item.text().unwrap_or_default().as_bytes(),
1275 )
1276 .ok();
1277 state.clipboard_item.replace(item);
1278 }
1279
1280 fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1281 let state = self.0.borrow_mut();
1282 state
1283 .clipboard
1284 .load(
1285 state.clipboard.getter.atoms.primary,
1286 state.clipboard.getter.atoms.utf8_string,
1287 state.clipboard.getter.atoms.property,
1288 Duration::from_secs(3),
1289 )
1290 .map(|text| crate::ClipboardItem::new_string(String::from_utf8(text).unwrap()))
1291 .ok()
1292 }
1293
1294 fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1295 let state = self.0.borrow_mut();
1296 // if the last copy was from this app, return our cached item
1297 // which has metadata attached.
1298 if state
1299 .clipboard
1300 .setter
1301 .connection
1302 .get_selection_owner(state.clipboard.setter.atoms.clipboard)
1303 .ok()
1304 .and_then(|r| r.reply().ok())
1305 .map(|reply| reply.owner == state.clipboard.setter.window)
1306 .unwrap_or(false)
1307 {
1308 return state.clipboard_item.clone();
1309 }
1310 state
1311 .clipboard
1312 .load(
1313 state.clipboard.getter.atoms.clipboard,
1314 state.clipboard.getter.atoms.utf8_string,
1315 state.clipboard.getter.atoms.property,
1316 Duration::from_secs(3),
1317 )
1318 .map(|text| crate::ClipboardItem::new_string(String::from_utf8(text).unwrap()))
1319 .ok()
1320 }
1321
1322 fn run(&self) {
1323 let mut event_loop = self
1324 .0
1325 .borrow_mut()
1326 .event_loop
1327 .take()
1328 .expect("App is already running");
1329
1330 event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1331 }
1332
1333 fn active_window(&self) -> Option<AnyWindowHandle> {
1334 let state = self.0.borrow();
1335 state.keyboard_focused_window.and_then(|focused_window| {
1336 state
1337 .windows
1338 .get(&focused_window)
1339 .map(|window| window.handle())
1340 })
1341 }
1342
1343 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1344 let state = self.0.borrow();
1345 let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1346
1347 let reply = state
1348 .xcb_connection
1349 .get_property(
1350 false,
1351 root,
1352 state.atoms._NET_CLIENT_LIST_STACKING,
1353 xproto::AtomEnum::WINDOW,
1354 0,
1355 u32::MAX,
1356 )
1357 .ok()?
1358 .reply()
1359 .ok()?;
1360
1361 let window_ids = reply
1362 .value
1363 .chunks_exact(4)
1364 .map(|chunk| u32::from_ne_bytes(chunk.try_into().unwrap()))
1365 .collect::<Vec<xproto::Window>>();
1366
1367 let mut handles = Vec::new();
1368
1369 // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1370 // a back-to-front order.
1371 // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1372 for window_ref in window_ids
1373 .iter()
1374 .rev()
1375 .filter_map(|&win| state.windows.get(&win))
1376 {
1377 if !window_ref.window.state.borrow().destroyed {
1378 handles.push(window_ref.handle());
1379 }
1380 }
1381
1382 Some(handles)
1383 }
1384}
1385
1386// Adatpted from:
1387// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1388pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1389 if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1390 return Duration::from_millis(16);
1391 }
1392
1393 let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1394 let micros = 1_000_000_000 / millihertz;
1395 log::info!("Refreshing at {} micros", micros);
1396 Duration::from_micros(micros)
1397}
1398
1399fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1400 value.integral as f32 + value.frac as f32 / u32::MAX as f32
1401}
1402
1403fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1404 // Method 1: Check for _NET_WM_CM_S{root}
1405 let atom_name = format!("_NET_WM_CM_S{}", root);
1406 let atom = xcb_connection
1407 .intern_atom(false, atom_name.as_bytes())
1408 .unwrap()
1409 .reply()
1410 .map(|reply| reply.atom)
1411 .unwrap_or(0);
1412
1413 let method1 = if atom != 0 {
1414 xcb_connection
1415 .get_selection_owner(atom)
1416 .unwrap()
1417 .reply()
1418 .map(|reply| reply.owner != 0)
1419 .unwrap_or(false)
1420 } else {
1421 false
1422 };
1423
1424 // Method 2: Check for _NET_WM_CM_OWNER
1425 let atom_name = "_NET_WM_CM_OWNER";
1426 let atom = xcb_connection
1427 .intern_atom(false, atom_name.as_bytes())
1428 .unwrap()
1429 .reply()
1430 .map(|reply| reply.atom)
1431 .unwrap_or(0);
1432
1433 let method2 = if atom != 0 {
1434 xcb_connection
1435 .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1436 .unwrap()
1437 .reply()
1438 .map(|reply| reply.value_len > 0)
1439 .unwrap_or(false)
1440 } else {
1441 false
1442 };
1443
1444 // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1445 let atom_name = "_NET_SUPPORTING_WM_CHECK";
1446 let atom = xcb_connection
1447 .intern_atom(false, atom_name.as_bytes())
1448 .unwrap()
1449 .reply()
1450 .map(|reply| reply.atom)
1451 .unwrap_or(0);
1452
1453 let method3 = if atom != 0 {
1454 xcb_connection
1455 .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1456 .unwrap()
1457 .reply()
1458 .map(|reply| reply.value_len > 0)
1459 .unwrap_or(false)
1460 } else {
1461 false
1462 };
1463
1464 // TODO: Remove this
1465 log::info!(
1466 "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1467 method1,
1468 method2,
1469 method3
1470 );
1471
1472 method1 || method2 || method3
1473}
1474
1475fn check_gtk_frame_extents_supported(
1476 xcb_connection: &XCBConnection,
1477 atoms: &XcbAtoms,
1478 root: xproto::Window,
1479) -> bool {
1480 let supported_atoms = xcb_connection
1481 .get_property(
1482 false,
1483 root,
1484 atoms._NET_SUPPORTED,
1485 xproto::AtomEnum::ATOM,
1486 0,
1487 1024,
1488 )
1489 .unwrap()
1490 .reply()
1491 .map(|reply| {
1492 // Convert Vec<u8> to Vec<u32>
1493 reply
1494 .value
1495 .chunks_exact(4)
1496 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1497 .collect::<Vec<u32>>()
1498 })
1499 .unwrap_or_default();
1500
1501 supported_atoms.contains(&atoms._GTK_FRAME_EXTENTS)
1502}