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