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