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