1use crate::Capslock;
2use core::str;
3use std::{
4 cell::RefCell,
5 collections::{BTreeMap, HashSet},
6 ops::Deref,
7 path::PathBuf,
8 rc::{Rc, Weak},
9 time::{Duration, Instant},
10};
11
12use anyhow::{Context as _, anyhow};
13use calloop::{
14 EventLoop, LoopHandle, RegistrationToken,
15 generic::{FdWrapper, Generic},
16};
17use collections::HashMap;
18use futures::channel::oneshot;
19use http_client::Url;
20use log::Level;
21use smallvec::SmallVec;
22use util::ResultExt;
23
24use x11rb::{
25 connection::{Connection, RequestConnection},
26 cursor,
27 errors::ConnectionError,
28 protocol::randr::ConnectionExt as _,
29 protocol::xinput::ConnectionExt,
30 protocol::xkb::ConnectionExt as _,
31 protocol::xproto::{
32 AtomEnum, ChangeWindowAttributesAux, ClientMessageData, ClientMessageEvent,
33 ConnectionExt as _, EventMask, KeyPressEvent, Visibility,
34 },
35 protocol::{Event, randr, render, xinput, xkb, xproto},
36 resource_manager::Database,
37 wrapper::ConnectionExt as _,
38 xcb_ffi::XCBConnection,
39};
40use xim::{AttributeName, Client, InputStyle, x11rb::X11rbClient};
41use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
42use xkbcommon::xkb::{self as xkbc, LayoutIndex, ModMask, STATE_LAYOUT_EFFECTIVE};
43
44use super::{
45 ButtonOrScroll, ScrollDirection, X11Display, X11WindowStatePtr, XcbAtoms, XimCallbackEvent,
46 XimHandler, button_or_scroll_from_event_detail, check_reply,
47 clipboard::{self, Clipboard},
48 get_reply, get_valuator_axis_index, handle_connection_error, modifiers_from_state,
49 pressed_button_from_mask,
50};
51
52use crate::platform::{
53 LinuxCommon, PlatformWindow,
54 blade::BladeContext,
55 linux::{
56 DEFAULT_CURSOR_ICON_NAME, LinuxClient, get_xkb_compose_state, is_within_click_distance,
57 log_cursor_icon_warning, open_uri_internal,
58 platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES},
59 reveal_path_internal,
60 xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
61 },
62 scap_screen_capture::scap_screen_sources,
63};
64use crate::{
65 AnyWindowHandle, Bounds, ClipboardItem, CursorStyle, DisplayId, FileDropEvent, Keystroke,
66 LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, Pixels, Platform,
67 PlatformDisplay, PlatformInput, PlatformKeyboardLayout, Point, RequestFrameOptions,
68 ScaledPixels, ScreenCaptureSource, ScrollDelta, Size, TouchPhase, WindowParams, X11Window,
69 modifiers_from_xinput_info, point, px,
70};
71
72/// Value for DeviceId parameters which selects all devices.
73pub(crate) const XINPUT_ALL_DEVICES: xinput::DeviceId = 0;
74
75/// Value for DeviceId parameters which selects all device groups. Events that
76/// occur within the group are emitted by the group itself.
77///
78/// In XInput 2's interface, these are referred to as "master devices", but that
79/// terminology is both archaic and unclear.
80pub(crate) const XINPUT_ALL_DEVICE_GROUPS: xinput::DeviceId = 1;
81
82pub(crate) struct WindowRef {
83 window: X11WindowStatePtr,
84 refresh_state: Option<RefreshState>,
85 expose_event_received: bool,
86 last_visibility: Visibility,
87 is_mapped: bool,
88}
89
90impl WindowRef {
91 pub fn handle(&self) -> AnyWindowHandle {
92 self.window.state.borrow().handle
93 }
94}
95
96impl Deref for WindowRef {
97 type Target = X11WindowStatePtr;
98
99 fn deref(&self) -> &Self::Target {
100 &self.window
101 }
102}
103
104enum RefreshState {
105 Hidden {
106 refresh_rate: Duration,
107 },
108 PeriodicRefresh {
109 refresh_rate: Duration,
110 event_loop_token: RegistrationToken,
111 },
112}
113
114#[derive(Debug)]
115#[non_exhaustive]
116pub enum EventHandlerError {
117 XCBConnectionError(ConnectionError),
118 XIMClientError(xim::ClientError),
119}
120
121impl std::error::Error for EventHandlerError {}
122
123impl std::fmt::Display for EventHandlerError {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 match self {
126 EventHandlerError::XCBConnectionError(err) => err.fmt(f),
127 EventHandlerError::XIMClientError(err) => err.fmt(f),
128 }
129 }
130}
131
132impl From<ConnectionError> for EventHandlerError {
133 fn from(err: ConnectionError) -> Self {
134 EventHandlerError::XCBConnectionError(err)
135 }
136}
137
138impl From<xim::ClientError> for EventHandlerError {
139 fn from(err: xim::ClientError) -> Self {
140 EventHandlerError::XIMClientError(err)
141 }
142}
143
144#[derive(Debug, Default, Clone)]
145struct XKBStateNotiy {
146 depressed_layout: LayoutIndex,
147 latched_layout: LayoutIndex,
148 locked_layout: LayoutIndex,
149}
150
151#[derive(Debug, Default)]
152pub struct Xdnd {
153 other_window: xproto::Window,
154 drag_type: u32,
155 retrieved: bool,
156 position: Point<Pixels>,
157}
158
159#[derive(Debug)]
160struct PointerDeviceState {
161 horizontal: ScrollAxisState,
162 vertical: ScrollAxisState,
163}
164
165#[derive(Debug, Default)]
166struct ScrollAxisState {
167 /// Valuator number for looking up this axis's scroll value.
168 valuator_number: Option<u16>,
169 /// Conversion factor from scroll units to lines.
170 multiplier: f32,
171 /// Last scroll value for calculating scroll delta.
172 ///
173 /// This gets set to `None` whenever it might be invalid - when devices change or when window focus changes.
174 /// The logic errs on the side of invalidating this, since the consequence is just skipping the delta of one scroll event.
175 /// The consequence of not invalidating it can be large invalid deltas, which are much more user visible.
176 scroll_value: Option<f32>,
177}
178
179pub struct X11ClientState {
180 pub(crate) loop_handle: LoopHandle<'static, X11Client>,
181 pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
182
183 pub(crate) last_click: Instant,
184 pub(crate) last_mouse_button: Option<MouseButton>,
185 pub(crate) last_location: Point<Pixels>,
186 pub(crate) current_count: usize,
187
188 gpu_context: BladeContext,
189
190 pub(crate) scale_factor: f32,
191
192 xkb_context: xkbc::Context,
193 pub(crate) xcb_connection: Rc<XCBConnection>,
194 xkb_device_id: i32,
195 client_side_decorations_supported: bool,
196 pub(crate) x_root_index: usize,
197 pub(crate) _resource_database: Database,
198 pub(crate) atoms: XcbAtoms,
199 pub(crate) windows: HashMap<xproto::Window, WindowRef>,
200 pub(crate) mouse_focused_window: Option<xproto::Window>,
201 pub(crate) keyboard_focused_window: Option<xproto::Window>,
202 pub(crate) xkb: xkbc::State,
203 previous_xkb_state: XKBStateNotiy,
204 keyboard_layout: LinuxKeyboardLayout,
205 pub(crate) ximc: Option<X11rbClient<Rc<XCBConnection>>>,
206 pub(crate) xim_handler: Option<XimHandler>,
207 pub modifiers: Modifiers,
208 pub capslock: Capslock,
209 // TODO: Can the other updates to `modifiers` be removed so that this is unnecessary?
210 // capslock logic was done analog to modifiers
211 pub last_modifiers_changed_event: Modifiers,
212 pub last_capslock_changed_event: Capslock,
213
214 pub(crate) compose_state: Option<xkbc::compose::State>,
215 pub(crate) pre_edit_text: Option<String>,
216 pub(crate) composing: bool,
217 pub(crate) pre_key_char_down: Option<Keystroke>,
218 pub(crate) cursor_handle: cursor::Handle,
219 pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
220 pub(crate) cursor_cache: HashMap<CursorStyle, Option<xproto::Cursor>>,
221
222 pointer_device_states: BTreeMap<xinput::DeviceId, PointerDeviceState>,
223
224 pub(crate) common: LinuxCommon,
225 pub(crate) clipboard: Clipboard,
226 pub(crate) clipboard_item: Option<ClipboardItem>,
227 pub(crate) xdnd_state: Xdnd,
228}
229
230#[derive(Clone)]
231pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
232
233impl X11ClientStatePtr {
234 fn get_client(&self) -> Option<X11Client> {
235 self.0.upgrade().map(X11Client)
236 }
237
238 pub fn drop_window(&self, x_window: u32) {
239 let Some(client) = self.get_client() else {
240 return;
241 };
242 let mut state = client.0.borrow_mut();
243
244 if let Some(window_ref) = state.windows.remove(&x_window) {
245 match window_ref.refresh_state {
246 Some(RefreshState::PeriodicRefresh {
247 event_loop_token, ..
248 }) => {
249 state.loop_handle.remove(event_loop_token);
250 }
251 _ => {}
252 }
253 }
254 if state.mouse_focused_window == Some(x_window) {
255 state.mouse_focused_window = None;
256 }
257 if state.keyboard_focused_window == Some(x_window) {
258 state.keyboard_focused_window = None;
259 }
260 state.cursor_styles.remove(&x_window);
261
262 if state.windows.is_empty() {
263 state.common.signal.stop();
264 }
265 }
266
267 pub fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
268 let Some(client) = self.get_client() else {
269 return;
270 };
271 let mut state = client.0.borrow_mut();
272 if state.composing || state.ximc.is_none() {
273 return;
274 }
275
276 let Some(mut ximc) = state.ximc.take() else {
277 log::error!("bug: xim connection not set");
278 return;
279 };
280 let Some(xim_handler) = state.xim_handler.take() else {
281 log::error!("bug: xim handler not set");
282 state.ximc = Some(ximc);
283 return;
284 };
285 let ic_attributes = ximc
286 .build_ic_attributes()
287 .push(
288 xim::AttributeName::InputStyle,
289 xim::InputStyle::PREEDIT_CALLBACKS,
290 )
291 .push(xim::AttributeName::ClientWindow, xim_handler.window)
292 .push(xim::AttributeName::FocusWindow, xim_handler.window)
293 .nested_list(xim::AttributeName::PreeditAttributes, |b| {
294 b.push(
295 xim::AttributeName::SpotLocation,
296 xim::Point {
297 x: u32::from(bounds.origin.x + bounds.size.width) as i16,
298 y: u32::from(bounds.origin.y + bounds.size.height) as i16,
299 },
300 );
301 })
302 .build();
303 let _ = ximc
304 .set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
305 .log_err();
306 state.ximc = Some(ximc);
307 state.xim_handler = Some(xim_handler);
308 }
309}
310
311#[derive(Clone)]
312pub(crate) struct X11Client(Rc<RefCell<X11ClientState>>);
313
314impl X11Client {
315 pub(crate) fn new() -> anyhow::Result<Self> {
316 let event_loop = EventLoop::try_new()?;
317
318 let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
319
320 let handle = event_loop.handle();
321
322 handle
323 .insert_source(main_receiver, {
324 let handle = handle.clone();
325 move |event, _, _: &mut X11Client| {
326 if let calloop::channel::Event::Msg(runnable) = event {
327 // Insert the runnables as idle callbacks, so we make sure that user-input and X11
328 // events have higher priority and runnables are only worked off after the event
329 // callbacks.
330 handle.insert_idle(|_| {
331 runnable.run();
332 });
333 }
334 }
335 })
336 .map_err(|err| {
337 anyhow!("Failed to initialize event loop handling of foreground tasks: {err:?}")
338 })?;
339
340 let (xcb_connection, x_root_index) = XCBConnection::connect(None)?;
341 xcb_connection.prefetch_extension_information(xkb::X11_EXTENSION_NAME)?;
342 xcb_connection.prefetch_extension_information(randr::X11_EXTENSION_NAME)?;
343 xcb_connection.prefetch_extension_information(render::X11_EXTENSION_NAME)?;
344 xcb_connection.prefetch_extension_information(xinput::X11_EXTENSION_NAME)?;
345
346 // Announce to X server that XInput up to 2.1 is supported. To increase this to 2.2 and
347 // beyond, support for touch events would need to be added.
348 let xinput_version = get_reply(
349 || "XInput XiQueryVersion failed",
350 xcb_connection.xinput_xi_query_version(2, 1),
351 )?;
352 assert!(
353 xinput_version.major_version >= 2,
354 "XInput version >= 2 required."
355 );
356
357 let pointer_device_states =
358 current_pointer_device_states(&xcb_connection, &BTreeMap::new()).unwrap_or_default();
359
360 let atoms = XcbAtoms::new(&xcb_connection)
361 .context("Failed to get XCB atoms")?
362 .reply()
363 .context("Failed to get XCB atoms")?;
364
365 let root = xcb_connection.setup().roots[0].root;
366 let compositor_present = check_compositor_present(&xcb_connection, root);
367 let gtk_frame_extents_supported =
368 check_gtk_frame_extents_supported(&xcb_connection, &atoms, root);
369 let client_side_decorations_supported = compositor_present && gtk_frame_extents_supported;
370 log::info!(
371 "x11: compositor present: {}, gtk_frame_extents_supported: {}",
372 compositor_present,
373 gtk_frame_extents_supported
374 );
375
376 let xkb = get_reply(
377 || "Failed to initialize XKB extension",
378 xcb_connection
379 .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION),
380 )?;
381
382 let events = xkb::EventType::STATE_NOTIFY
383 | xkb::EventType::MAP_NOTIFY
384 | xkb::EventType::NEW_KEYBOARD_NOTIFY;
385 let map_notify_parts = xkb::MapPart::KEY_TYPES
386 | xkb::MapPart::KEY_SYMS
387 | xkb::MapPart::MODIFIER_MAP
388 | xkb::MapPart::EXPLICIT_COMPONENTS
389 | xkb::MapPart::KEY_ACTIONS
390 | xkb::MapPart::KEY_BEHAVIORS
391 | xkb::MapPart::VIRTUAL_MODS
392 | xkb::MapPart::VIRTUAL_MOD_MAP;
393 check_reply(
394 || "Failed to select XKB events",
395 xcb_connection.xkb_select_events(
396 xkb::ID::USE_CORE_KBD.into(),
397 0u8.into(),
398 events,
399 map_notify_parts,
400 map_notify_parts,
401 &xkb::SelectEventsAux::new(),
402 ),
403 )?;
404 assert!(xkb.supported);
405
406 let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
407 let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
408 let xkb_state = {
409 let xkb_keymap = xkbc::x11::keymap_new_from_device(
410 &xkb_context,
411 &xcb_connection,
412 xkb_device_id,
413 xkbc::KEYMAP_COMPILE_NO_FLAGS,
414 );
415 xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
416 };
417 let compose_state = get_xkb_compose_state(&xkb_context);
418 let layout_idx = xkb_state.serialize_layout(STATE_LAYOUT_EFFECTIVE);
419 let layout_name = xkb_state
420 .get_keymap()
421 .layout_get_name(layout_idx)
422 .to_string();
423 let keyboard_layout = LinuxKeyboardLayout::new(layout_name.into());
424
425 let gpu_context = BladeContext::new().context("Unable to init GPU context")?;
426
427 let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection)
428 .context("Failed to create resource database")?;
429 let scale_factor = resource_database
430 .get_value("Xft.dpi", "Xft.dpi")
431 .ok()
432 .flatten()
433 .map(|dpi: f32| dpi / 96.0)
434 .unwrap_or(1.0);
435 let cursor_handle = cursor::Handle::new(&xcb_connection, x_root_index, &resource_database)
436 .context("Failed to initialize cursor theme handler")?
437 .reply()
438 .context("Failed to initialize cursor theme handler")?;
439
440 let clipboard = Clipboard::new().context("Failed to initialize clipboard")?;
441
442 let xcb_connection = Rc::new(xcb_connection);
443
444 let ximc = X11rbClient::init(Rc::clone(&xcb_connection), x_root_index, None).ok();
445 let xim_handler = if ximc.is_some() {
446 Some(XimHandler::new())
447 } else {
448 None
449 };
450
451 // Safety: Safe if xcb::Connection always returns a valid fd
452 let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
453
454 handle
455 .insert_source(
456 Generic::new_with_error::<EventHandlerError>(
457 fd,
458 calloop::Interest::READ,
459 calloop::Mode::Level,
460 ),
461 {
462 let xcb_connection = xcb_connection.clone();
463 move |_readiness, _, client| {
464 client.process_x11_events(&xcb_connection)?;
465 Ok(calloop::PostAction::Continue)
466 }
467 },
468 )
469 .map_err(|err| anyhow!("Failed to initialize X11 event source: {err:?}"))?;
470
471 handle
472 .insert_source(XDPEventSource::new(&common.background_executor), {
473 move |event, _, client| match event {
474 XDPEvent::WindowAppearance(appearance) => {
475 client.with_common(|common| common.appearance = appearance);
476 for (_, window) in &mut client.0.borrow_mut().windows {
477 window.window.set_appearance(appearance);
478 }
479 }
480 XDPEvent::CursorTheme(_) | XDPEvent::CursorSize(_) => {
481 // noop, X11 manages this for us.
482 }
483 }
484 })
485 .map_err(|err| anyhow!("Failed to initialize XDP event source: {err:?}"))?;
486
487 Ok(X11Client(Rc::new(RefCell::new(X11ClientState {
488 modifiers: Modifiers::default(),
489 capslock: Capslock::default(),
490 last_modifiers_changed_event: Modifiers::default(),
491 last_capslock_changed_event: Capslock::default(),
492 event_loop: Some(event_loop),
493 loop_handle: handle,
494 common,
495 last_click: Instant::now(),
496 last_mouse_button: None,
497 last_location: Point::new(px(0.0), px(0.0)),
498 current_count: 0,
499 gpu_context,
500 scale_factor,
501
502 xkb_context,
503 xcb_connection,
504 xkb_device_id,
505 client_side_decorations_supported,
506 x_root_index,
507 _resource_database: resource_database,
508 atoms,
509 windows: HashMap::default(),
510 mouse_focused_window: None,
511 keyboard_focused_window: None,
512 xkb: xkb_state,
513 previous_xkb_state: XKBStateNotiy::default(),
514 keyboard_layout,
515 ximc,
516 xim_handler,
517
518 compose_state,
519 pre_edit_text: None,
520 pre_key_char_down: None,
521 composing: false,
522
523 cursor_handle,
524 cursor_styles: HashMap::default(),
525 cursor_cache: HashMap::default(),
526
527 pointer_device_states,
528
529 clipboard,
530 clipboard_item: None,
531 xdnd_state: Xdnd::default(),
532 }))))
533 }
534
535 pub fn process_x11_events(
536 &self,
537 xcb_connection: &XCBConnection,
538 ) -> Result<(), EventHandlerError> {
539 loop {
540 let mut events = Vec::new();
541 let mut windows_to_refresh = HashSet::new();
542
543 let mut last_key_release = None;
544 let mut last_key_press: Option<KeyPressEvent> = None;
545
546 // event handlers for new keyboard / remapping refresh the state without using event
547 // details, this deduplicates them.
548 let mut last_keymap_change_event: Option<Event> = None;
549
550 loop {
551 match xcb_connection.poll_for_event() {
552 Ok(Some(event)) => {
553 match event {
554 Event::Expose(expose_event) => {
555 windows_to_refresh.insert(expose_event.window);
556 }
557 Event::KeyRelease(_) => {
558 if let Some(last_keymap_change_event) =
559 last_keymap_change_event.take()
560 {
561 if let Some(last_key_release) = last_key_release.take() {
562 events.push(last_key_release);
563 }
564 last_key_press = None;
565 events.push(last_keymap_change_event);
566 }
567
568 last_key_release = Some(event);
569 }
570 Event::KeyPress(key_press) => {
571 if let Some(last_keymap_change_event) =
572 last_keymap_change_event.take()
573 {
574 if let Some(last_key_release) = last_key_release.take() {
575 events.push(last_key_release);
576 }
577 last_key_press = None;
578 events.push(last_keymap_change_event);
579 }
580
581 if let Some(last_press) = last_key_press.as_ref() {
582 if last_press.detail == key_press.detail {
583 continue;
584 }
585 }
586
587 if let Some(Event::KeyRelease(key_release)) =
588 last_key_release.take()
589 {
590 // We ignore that last KeyRelease if it's too close to this KeyPress,
591 // suggesting that it's auto-generated by X11 as a key-repeat event.
592 if key_release.detail != key_press.detail
593 || key_press.time.saturating_sub(key_release.time) > 20
594 {
595 events.push(Event::KeyRelease(key_release));
596 }
597 }
598 events.push(Event::KeyPress(key_press));
599 last_key_press = Some(key_press);
600 }
601 Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
602 if let Some(release_event) = last_key_release.take() {
603 events.push(release_event);
604 }
605 last_keymap_change_event = Some(event);
606 }
607 _ => {
608 if let Some(release_event) = last_key_release.take() {
609 events.push(release_event);
610 }
611 events.push(event);
612 }
613 }
614 }
615 Ok(None) => {
616 break;
617 }
618 Err(err) => {
619 let err = handle_connection_error(err);
620 log::warn!("error while polling for X11 events: {err:?}");
621 break;
622 }
623 }
624 }
625
626 if let Some(release_event) = last_key_release.take() {
627 events.push(release_event);
628 }
629 if let Some(keymap_change_event) = last_keymap_change_event.take() {
630 events.push(keymap_change_event);
631 }
632
633 if events.is_empty() && windows_to_refresh.is_empty() {
634 break;
635 }
636
637 for window in windows_to_refresh.into_iter() {
638 let mut state = self.0.borrow_mut();
639 if let Some(window) = state.windows.get_mut(&window) {
640 window.expose_event_received = true;
641 }
642 }
643
644 for event in events.into_iter() {
645 let mut state = self.0.borrow_mut();
646 if !state.has_xim() {
647 drop(state);
648 self.handle_event(event);
649 continue;
650 }
651
652 let Some((mut ximc, mut xim_handler)) = state.take_xim() else {
653 continue;
654 };
655 let xim_connected = xim_handler.connected;
656 drop(state);
657
658 let xim_filtered = match ximc.filter_event(&event, &mut xim_handler) {
659 Ok(handled) => handled,
660 Err(err) => {
661 log::error!("XIMClientError: {}", err);
662 false
663 }
664 };
665 let xim_callback_event = xim_handler.last_callback_event.take();
666
667 let mut state = self.0.borrow_mut();
668 state.restore_xim(ximc, xim_handler);
669 drop(state);
670
671 if let Some(event) = xim_callback_event {
672 self.handle_xim_callback_event(event);
673 }
674
675 if xim_filtered {
676 continue;
677 }
678
679 if xim_connected {
680 self.xim_handle_event(event);
681 } else {
682 self.handle_event(event);
683 }
684 }
685 }
686 Ok(())
687 }
688
689 pub fn enable_ime(&self) {
690 let mut state = self.0.borrow_mut();
691 if !state.has_xim() {
692 return;
693 }
694
695 let Some((mut ximc, mut xim_handler)) = state.take_xim() else {
696 return;
697 };
698 let mut ic_attributes = ximc
699 .build_ic_attributes()
700 .push(AttributeName::InputStyle, InputStyle::PREEDIT_CALLBACKS)
701 .push(AttributeName::ClientWindow, xim_handler.window)
702 .push(AttributeName::FocusWindow, xim_handler.window);
703
704 let window_id = state.keyboard_focused_window;
705 drop(state);
706 if let Some(window_id) = window_id {
707 let Some(window) = self.get_window(window_id) else {
708 log::error!("Failed to get window for IME positioning");
709 let mut state = self.0.borrow_mut();
710 state.ximc = Some(ximc);
711 state.xim_handler = Some(xim_handler);
712 return;
713 };
714 if let Some(area) = window.get_ime_area() {
715 ic_attributes =
716 ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
717 b.push(
718 xim::AttributeName::SpotLocation,
719 xim::Point {
720 x: u32::from(area.origin.x + area.size.width) as i16,
721 y: u32::from(area.origin.y + area.size.height) as i16,
722 },
723 );
724 });
725 }
726 }
727 ximc.create_ic(xim_handler.im_id, ic_attributes.build())
728 .ok();
729 let mut state = self.0.borrow_mut();
730 state.restore_xim(ximc, xim_handler);
731 }
732
733 pub fn reset_ime(&self) {
734 let mut state = self.0.borrow_mut();
735 state.composing = false;
736 if let Some(mut ximc) = state.ximc.take() {
737 if let Some(xim_handler) = state.xim_handler.as_ref() {
738 ximc.reset_ic(xim_handler.im_id, xim_handler.ic_id).ok();
739 } else {
740 log::error!("bug: xim handler not set in reset_ime");
741 }
742 state.ximc = Some(ximc);
743 }
744 }
745
746 fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
747 let state = self.0.borrow();
748 state
749 .windows
750 .get(&win)
751 .filter(|window_reference| !window_reference.window.state.borrow().destroyed)
752 .map(|window_reference| window_reference.window.clone())
753 }
754
755 fn handle_event(&self, event: Event) -> Option<()> {
756 match event {
757 Event::UnmapNotify(event) => {
758 let mut state = self.0.borrow_mut();
759 if let Some(window_ref) = state.windows.get_mut(&event.window) {
760 window_ref.is_mapped = false;
761 }
762 state.update_refresh_loop(event.window);
763 }
764 Event::MapNotify(event) => {
765 let mut state = self.0.borrow_mut();
766 if let Some(window_ref) = state.windows.get_mut(&event.window) {
767 window_ref.is_mapped = true;
768 }
769 state.update_refresh_loop(event.window);
770 }
771 Event::VisibilityNotify(event) => {
772 let mut state = self.0.borrow_mut();
773 if let Some(window_ref) = state.windows.get_mut(&event.window) {
774 window_ref.last_visibility = event.state;
775 }
776 state.update_refresh_loop(event.window);
777 }
778 Event::ClientMessage(event) => {
779 let window = self.get_window(event.window)?;
780 let [atom, arg1, arg2, arg3, arg4] = event.data.as_data32();
781 let mut state = self.0.borrow_mut();
782
783 if atom == state.atoms.WM_DELETE_WINDOW {
784 // window "x" button clicked by user
785 if window.should_close() {
786 // Rest of the close logic is handled in drop_window()
787 window.close();
788 }
789 } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
790 window.state.borrow_mut().last_sync_counter =
791 Some(x11rb::protocol::sync::Int64 {
792 lo: arg2,
793 hi: arg3 as i32,
794 })
795 }
796
797 if event.type_ == state.atoms.XdndEnter {
798 state.xdnd_state.other_window = atom;
799 if (arg1 & 0x1) == 0x1 {
800 state.xdnd_state.drag_type = xdnd_get_supported_atom(
801 &state.xcb_connection,
802 &state.atoms,
803 state.xdnd_state.other_window,
804 );
805 } else {
806 if let Some(atom) = [arg2, arg3, arg4]
807 .into_iter()
808 .find(|atom| xdnd_is_atom_supported(*atom, &state.atoms))
809 {
810 state.xdnd_state.drag_type = atom;
811 }
812 }
813 } else if event.type_ == state.atoms.XdndLeave {
814 let position = state.xdnd_state.position;
815 drop(state);
816 window
817 .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
818 window.handle_input(PlatformInput::FileDrop(FileDropEvent::Exited {}));
819 self.0.borrow_mut().xdnd_state = Xdnd::default();
820 } else if event.type_ == state.atoms.XdndPosition {
821 if let Ok(pos) = get_reply(
822 || "Failed to query pointer position",
823 state.xcb_connection.query_pointer(event.window),
824 ) {
825 state.xdnd_state.position =
826 Point::new(Pixels(pos.win_x as f32), Pixels(pos.win_y as f32));
827 }
828 if !state.xdnd_state.retrieved {
829 check_reply(
830 || "Failed to convert selection for drag and drop",
831 state.xcb_connection.convert_selection(
832 event.window,
833 state.atoms.XdndSelection,
834 state.xdnd_state.drag_type,
835 state.atoms.XDND_DATA,
836 arg3,
837 ),
838 )
839 .log_err();
840 }
841 xdnd_send_status(
842 &state.xcb_connection,
843 &state.atoms,
844 event.window,
845 state.xdnd_state.other_window,
846 arg4,
847 );
848 let position = state.xdnd_state.position;
849 drop(state);
850 window
851 .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
852 } else if event.type_ == state.atoms.XdndDrop {
853 xdnd_send_finished(
854 &state.xcb_connection,
855 &state.atoms,
856 event.window,
857 state.xdnd_state.other_window,
858 );
859 let position = state.xdnd_state.position;
860 drop(state);
861 window
862 .handle_input(PlatformInput::FileDrop(FileDropEvent::Submit { position }));
863 self.0.borrow_mut().xdnd_state = Xdnd::default();
864 }
865 }
866 Event::SelectionNotify(event) => {
867 let window = self.get_window(event.requestor)?;
868 let mut state = self.0.borrow_mut();
869 let reply = get_reply(
870 || "Failed to get XDND_DATA",
871 state.xcb_connection.get_property(
872 false,
873 event.requestor,
874 state.atoms.XDND_DATA,
875 AtomEnum::ANY,
876 0,
877 1024,
878 ),
879 )
880 .log_err();
881 let Some(reply) = reply else {
882 return Some(());
883 };
884 match str::from_utf8(&reply.value) {
885 Ok(file_list) => {
886 let paths: SmallVec<[_; 2]> = file_list
887 .lines()
888 .filter_map(|path| Url::parse(path).log_err())
889 .filter_map(|url| url.to_file_path().log_err())
890 .collect();
891 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
892 position: state.xdnd_state.position,
893 paths: crate::ExternalPaths(paths),
894 });
895 drop(state);
896 window.handle_input(input);
897 self.0.borrow_mut().xdnd_state.retrieved = true;
898 }
899 Err(_) => {}
900 }
901 }
902 Event::ConfigureNotify(event) => {
903 let bounds = Bounds {
904 origin: Point {
905 x: event.x.into(),
906 y: event.y.into(),
907 },
908 size: Size {
909 width: event.width.into(),
910 height: event.height.into(),
911 },
912 };
913 let window = self.get_window(event.window)?;
914 window
915 .set_bounds(bounds)
916 .context("X11: Failed to set window bounds")
917 .log_err();
918 }
919 Event::PropertyNotify(event) => {
920 let window = self.get_window(event.window)?;
921 window
922 .property_notify(event)
923 .context("X11: Failed to handle property notify")
924 .log_err();
925 }
926 Event::FocusIn(event) => {
927 let window = self.get_window(event.event)?;
928 window.set_active(true);
929 let mut state = self.0.borrow_mut();
930 state.keyboard_focused_window = Some(event.event);
931 if let Some(handler) = state.xim_handler.as_mut() {
932 handler.window = event.event;
933 }
934 drop(state);
935 self.enable_ime();
936 }
937 Event::FocusOut(event) => {
938 let window = self.get_window(event.event)?;
939 window.set_active(false);
940 let mut state = self.0.borrow_mut();
941 state.keyboard_focused_window = None;
942 if let Some(compose_state) = state.compose_state.as_mut() {
943 compose_state.reset();
944 }
945 state.pre_edit_text.take();
946 drop(state);
947 self.reset_ime();
948 window.handle_ime_delete();
949 }
950 Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
951 let mut state = self.0.borrow_mut();
952 let xkb_state = {
953 let xkb_keymap = xkbc::x11::keymap_new_from_device(
954 &state.xkb_context,
955 &state.xcb_connection,
956 state.xkb_device_id,
957 xkbc::KEYMAP_COMPILE_NO_FLAGS,
958 );
959 xkbc::x11::state_new_from_device(
960 &xkb_keymap,
961 &state.xcb_connection,
962 state.xkb_device_id,
963 )
964 };
965 let depressed_layout = xkb_state.serialize_layout(xkbc::STATE_LAYOUT_DEPRESSED);
966 let latched_layout = xkb_state.serialize_layout(xkbc::STATE_LAYOUT_LATCHED);
967 let locked_layout = xkb_state.serialize_layout(xkbc::ffi::XKB_STATE_LAYOUT_LOCKED);
968 state.previous_xkb_state = XKBStateNotiy {
969 depressed_layout,
970 latched_layout,
971 locked_layout,
972 };
973 state.xkb = xkb_state;
974 drop(state);
975 self.handle_keyboard_layout_change();
976 }
977 Event::XkbStateNotify(event) => {
978 let mut state = self.0.borrow_mut();
979 let old_layout = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
980 let new_layout = u32::from(event.group);
981 state.xkb.update_mask(
982 event.base_mods.into(),
983 event.latched_mods.into(),
984 event.locked_mods.into(),
985 event.base_group as u32,
986 event.latched_group as u32,
987 event.locked_group.into(),
988 );
989 state.previous_xkb_state = XKBStateNotiy {
990 depressed_layout: event.base_group as u32,
991 latched_layout: event.latched_group as u32,
992 locked_layout: event.locked_group.into(),
993 };
994
995 let modifiers = Modifiers::from_xkb(&state.xkb);
996 let capslock = Capslock::from_xkb(&state.xkb);
997 if state.last_modifiers_changed_event == modifiers
998 && state.last_capslock_changed_event == capslock
999 {
1000 drop(state);
1001 } else {
1002 let focused_window_id = state.keyboard_focused_window?;
1003 state.modifiers = modifiers;
1004 state.last_modifiers_changed_event = modifiers;
1005 state.capslock = capslock;
1006 state.last_capslock_changed_event = capslock;
1007 drop(state);
1008
1009 let focused_window = self.get_window(focused_window_id)?;
1010 focused_window.handle_input(PlatformInput::ModifiersChanged(
1011 ModifiersChangedEvent {
1012 modifiers,
1013 capslock,
1014 },
1015 ));
1016 }
1017
1018 if new_layout != old_layout {
1019 self.handle_keyboard_layout_change();
1020 }
1021 }
1022 Event::KeyPress(event) => {
1023 let window = self.get_window(event.event)?;
1024 let mut state = self.0.borrow_mut();
1025
1026 let modifiers = modifiers_from_state(event.state);
1027 state.modifiers = modifiers;
1028 state.pre_key_char_down.take();
1029 let keystroke = {
1030 let code = event.detail.into();
1031 let xkb_state = state.previous_xkb_state.clone();
1032 state.xkb.update_mask(
1033 event.state.bits() as ModMask,
1034 0,
1035 0,
1036 xkb_state.depressed_layout,
1037 xkb_state.latched_layout,
1038 xkb_state.locked_layout,
1039 );
1040 let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
1041 let keysym = state.xkb.key_get_one_sym(code);
1042 if keysym.is_modifier_key() {
1043 return Some(());
1044 }
1045 if let Some(mut compose_state) = state.compose_state.take() {
1046 compose_state.feed(keysym);
1047 match compose_state.status() {
1048 xkbc::Status::Composed => {
1049 state.pre_edit_text.take();
1050 keystroke.key_char = compose_state.utf8();
1051 if let Some(keysym) = compose_state.keysym() {
1052 keystroke.key = xkbc::keysym_get_name(keysym);
1053 }
1054 }
1055 xkbc::Status::Composing => {
1056 keystroke.key_char = None;
1057 state.pre_edit_text = compose_state
1058 .utf8()
1059 .or(crate::Keystroke::underlying_dead_key(keysym));
1060 let pre_edit =
1061 state.pre_edit_text.clone().unwrap_or(String::default());
1062 drop(state);
1063 window.handle_ime_preedit(pre_edit);
1064 state = self.0.borrow_mut();
1065 }
1066 xkbc::Status::Cancelled => {
1067 let pre_edit = state.pre_edit_text.take();
1068 drop(state);
1069 if let Some(pre_edit) = pre_edit {
1070 window.handle_ime_commit(pre_edit);
1071 }
1072 if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
1073 window.handle_ime_preedit(current_key);
1074 }
1075 state = self.0.borrow_mut();
1076 compose_state.feed(keysym);
1077 }
1078 _ => {}
1079 }
1080 state.compose_state = Some(compose_state);
1081 }
1082 keystroke
1083 };
1084 drop(state);
1085 window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1086 keystroke,
1087 is_held: false,
1088 }));
1089 }
1090 Event::KeyRelease(event) => {
1091 let window = self.get_window(event.event)?;
1092 let mut state = self.0.borrow_mut();
1093
1094 let modifiers = modifiers_from_state(event.state);
1095 state.modifiers = modifiers;
1096
1097 let keystroke = {
1098 let code = event.detail.into();
1099 let xkb_state = state.previous_xkb_state.clone();
1100 state.xkb.update_mask(
1101 event.state.bits() as ModMask,
1102 0,
1103 0,
1104 xkb_state.depressed_layout,
1105 xkb_state.latched_layout,
1106 xkb_state.locked_layout,
1107 );
1108 let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
1109 let keysym = state.xkb.key_get_one_sym(code);
1110 if keysym.is_modifier_key() {
1111 return Some(());
1112 }
1113 keystroke
1114 };
1115 drop(state);
1116 window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
1117 }
1118 Event::XinputButtonPress(event) => {
1119 let window = self.get_window(event.event)?;
1120 let mut state = self.0.borrow_mut();
1121
1122 let modifiers = modifiers_from_xinput_info(event.mods);
1123 state.modifiers = modifiers;
1124
1125 let position = point(
1126 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1127 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1128 );
1129
1130 if state.composing && state.ximc.is_some() {
1131 drop(state);
1132 self.reset_ime();
1133 window.handle_ime_unmark();
1134 state = self.0.borrow_mut();
1135 } else if let Some(text) = state.pre_edit_text.take() {
1136 if let Some(compose_state) = state.compose_state.as_mut() {
1137 compose_state.reset();
1138 }
1139 drop(state);
1140 window.handle_ime_commit(text);
1141 state = self.0.borrow_mut();
1142 }
1143 match button_or_scroll_from_event_detail(event.detail) {
1144 Some(ButtonOrScroll::Button(button)) => {
1145 let click_elapsed = state.last_click.elapsed();
1146 if click_elapsed < DOUBLE_CLICK_INTERVAL
1147 && state
1148 .last_mouse_button
1149 .is_some_and(|prev_button| prev_button == button)
1150 && is_within_click_distance(state.last_location, position)
1151 {
1152 state.current_count += 1;
1153 } else {
1154 state.current_count = 1;
1155 }
1156
1157 state.last_click = Instant::now();
1158 state.last_mouse_button = Some(button);
1159 state.last_location = position;
1160 let current_count = state.current_count;
1161
1162 drop(state);
1163 window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
1164 button,
1165 position,
1166 modifiers,
1167 click_count: current_count,
1168 first_mouse: false,
1169 }));
1170 }
1171 Some(ButtonOrScroll::Scroll(direction)) => {
1172 drop(state);
1173 // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1174 // Since handling those events does the scrolling, they are skipped here.
1175 if !event
1176 .flags
1177 .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1178 {
1179 let scroll_delta = match direction {
1180 ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1181 ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1182 ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1183 ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1184 };
1185 window.handle_input(PlatformInput::ScrollWheel(
1186 make_scroll_wheel_event(position, scroll_delta, modifiers),
1187 ));
1188 }
1189 }
1190 None => {
1191 log::error!("Unknown x11 button: {}", event.detail);
1192 }
1193 }
1194 }
1195 Event::XinputButtonRelease(event) => {
1196 let window = self.get_window(event.event)?;
1197 let mut state = self.0.borrow_mut();
1198 let modifiers = modifiers_from_xinput_info(event.mods);
1199 state.modifiers = modifiers;
1200
1201 let position = point(
1202 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1203 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1204 );
1205 match button_or_scroll_from_event_detail(event.detail) {
1206 Some(ButtonOrScroll::Button(button)) => {
1207 let click_count = state.current_count;
1208 drop(state);
1209 window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
1210 button,
1211 position,
1212 modifiers,
1213 click_count,
1214 }));
1215 }
1216 Some(ButtonOrScroll::Scroll(_)) => {}
1217 None => {}
1218 }
1219 }
1220 Event::XinputMotion(event) => {
1221 let window = self.get_window(event.event)?;
1222 let mut state = self.0.borrow_mut();
1223 let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1224 let position = point(
1225 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1226 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1227 );
1228 let modifiers = modifiers_from_xinput_info(event.mods);
1229 state.modifiers = modifiers;
1230 drop(state);
1231
1232 if event.valuator_mask[0] & 3 != 0 {
1233 window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
1234 position,
1235 pressed_button,
1236 modifiers,
1237 }));
1238 }
1239
1240 state = self.0.borrow_mut();
1241 if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1242 let scroll_delta = get_scroll_delta_and_update_state(&mut pointer, &event);
1243 drop(state);
1244 if let Some(scroll_delta) = scroll_delta {
1245 window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1246 position,
1247 scroll_delta,
1248 modifiers,
1249 )));
1250 }
1251 }
1252 }
1253 Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1254 let window = self.get_window(event.event)?;
1255 window.set_hovered(true);
1256 let mut state = self.0.borrow_mut();
1257 state.mouse_focused_window = Some(event.event);
1258 }
1259 Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1260 let mut state = self.0.borrow_mut();
1261
1262 // Set last scroll values to `None` so that a large delta isn't created if scrolling is done outside the window (the valuator is global)
1263 reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1264 state.mouse_focused_window = None;
1265 let pressed_button = pressed_button_from_mask(event.buttons[0]);
1266 let position = point(
1267 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1268 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1269 );
1270 let modifiers = modifiers_from_xinput_info(event.mods);
1271 state.modifiers = modifiers;
1272 drop(state);
1273
1274 let window = self.get_window(event.event)?;
1275 window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
1276 pressed_button,
1277 position,
1278 modifiers,
1279 }));
1280 window.set_hovered(false);
1281 }
1282 Event::XinputHierarchy(event) => {
1283 let mut state = self.0.borrow_mut();
1284 // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1285 // Any change to a device invalidates its scroll values.
1286 for info in event.infos {
1287 if is_pointer_device(info.type_) {
1288 state.pointer_device_states.remove(&info.deviceid);
1289 }
1290 }
1291 if let Some(pointer_device_states) = current_pointer_device_states(
1292 &state.xcb_connection,
1293 &state.pointer_device_states,
1294 ) {
1295 state.pointer_device_states = pointer_device_states;
1296 }
1297 }
1298 Event::XinputDeviceChanged(event) => {
1299 let mut state = self.0.borrow_mut();
1300 if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1301 reset_pointer_device_scroll_positions(&mut pointer);
1302 }
1303 }
1304 _ => {}
1305 };
1306
1307 Some(())
1308 }
1309
1310 fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1311 match event {
1312 XimCallbackEvent::XimXEvent(event) => {
1313 self.handle_event(event);
1314 }
1315 XimCallbackEvent::XimCommitEvent(window, text) => {
1316 self.xim_handle_commit(window, text);
1317 }
1318 XimCallbackEvent::XimPreeditEvent(window, text) => {
1319 self.xim_handle_preedit(window, text);
1320 }
1321 };
1322 }
1323
1324 fn xim_handle_event(&self, event: Event) -> Option<()> {
1325 match event {
1326 Event::KeyPress(event) | Event::KeyRelease(event) => {
1327 let mut state = self.0.borrow_mut();
1328 state.pre_key_char_down = Some(Keystroke::from_xkb(
1329 &state.xkb,
1330 state.modifiers,
1331 event.detail.into(),
1332 ));
1333 let (mut ximc, mut xim_handler) = state.take_xim()?;
1334 drop(state);
1335 xim_handler.window = event.event;
1336 ximc.forward_event(
1337 xim_handler.im_id,
1338 xim_handler.ic_id,
1339 xim::ForwardEventFlag::empty(),
1340 &event,
1341 )
1342 .context("X11: Failed to forward XIM event")
1343 .log_err();
1344 let mut state = self.0.borrow_mut();
1345 state.restore_xim(ximc, xim_handler);
1346 drop(state);
1347 }
1348 event => {
1349 self.handle_event(event);
1350 }
1351 }
1352 Some(())
1353 }
1354
1355 fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1356 let Some(window) = self.get_window(window) else {
1357 log::error!("bug: Failed to get window for XIM commit");
1358 return None;
1359 };
1360 let mut state = self.0.borrow_mut();
1361 let keystroke = state.pre_key_char_down.take();
1362 state.composing = false;
1363 drop(state);
1364 if let Some(mut keystroke) = keystroke {
1365 keystroke.key_char = Some(text.clone());
1366 window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1367 keystroke,
1368 is_held: false,
1369 }));
1370 }
1371
1372 Some(())
1373 }
1374
1375 fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1376 let Some(window) = self.get_window(window) else {
1377 log::error!("bug: Failed to get window for XIM preedit");
1378 return None;
1379 };
1380
1381 let mut state = self.0.borrow_mut();
1382 let (mut ximc, mut xim_handler) = state.take_xim()?;
1383 state.composing = !text.is_empty();
1384 drop(state);
1385 window.handle_ime_preedit(text);
1386
1387 if let Some(area) = window.get_ime_area() {
1388 let ic_attributes = ximc
1389 .build_ic_attributes()
1390 .push(
1391 xim::AttributeName::InputStyle,
1392 xim::InputStyle::PREEDIT_CALLBACKS,
1393 )
1394 .push(xim::AttributeName::ClientWindow, xim_handler.window)
1395 .push(xim::AttributeName::FocusWindow, xim_handler.window)
1396 .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1397 b.push(
1398 xim::AttributeName::SpotLocation,
1399 xim::Point {
1400 x: u32::from(area.origin.x + area.size.width) as i16,
1401 y: u32::from(area.origin.y + area.size.height) as i16,
1402 },
1403 );
1404 })
1405 .build();
1406 ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1407 .ok();
1408 }
1409 let mut state = self.0.borrow_mut();
1410 state.restore_xim(ximc, xim_handler);
1411 drop(state);
1412 Some(())
1413 }
1414
1415 fn handle_keyboard_layout_change(&self) {
1416 let mut state = self.0.borrow_mut();
1417 let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1418 let keymap = state.xkb.get_keymap();
1419 let layout_name = keymap.layout_get_name(layout_idx);
1420 if layout_name != state.keyboard_layout.name() {
1421 state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1422 if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1423 drop(state);
1424 callback();
1425 state = self.0.borrow_mut();
1426 state.common.callbacks.keyboard_layout_change = Some(callback);
1427 }
1428 }
1429 }
1430}
1431
1432impl LinuxClient for X11Client {
1433 fn compositor_name(&self) -> &'static str {
1434 "X11"
1435 }
1436
1437 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1438 f(&mut self.0.borrow_mut().common)
1439 }
1440
1441 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1442 let state = self.0.borrow();
1443 Box::new(state.keyboard_layout.clone())
1444 }
1445
1446 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1447 let state = self.0.borrow();
1448 let setup = state.xcb_connection.setup();
1449 setup
1450 .roots
1451 .iter()
1452 .enumerate()
1453 .filter_map(|(root_id, _)| {
1454 Some(Rc::new(
1455 X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1456 ) as Rc<dyn PlatformDisplay>)
1457 })
1458 .collect()
1459 }
1460
1461 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1462 let state = self.0.borrow();
1463 X11Display::new(
1464 &state.xcb_connection,
1465 state.scale_factor,
1466 state.x_root_index,
1467 )
1468 .log_err()
1469 .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1470 }
1471
1472 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1473 let state = self.0.borrow();
1474
1475 Some(Rc::new(
1476 X11Display::new(&state.xcb_connection, state.scale_factor, id.0 as usize).ok()?,
1477 ))
1478 }
1479
1480 fn is_screen_capture_supported(&self) -> bool {
1481 true
1482 }
1483
1484 fn screen_capture_sources(
1485 &self,
1486 ) -> oneshot::Receiver<anyhow::Result<Vec<Box<dyn ScreenCaptureSource>>>> {
1487 scap_screen_sources(&self.0.borrow().common.foreground_executor)
1488 }
1489
1490 fn open_window(
1491 &self,
1492 handle: AnyWindowHandle,
1493 params: WindowParams,
1494 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1495 let mut state = self.0.borrow_mut();
1496 let x_window = state
1497 .xcb_connection
1498 .generate_id()
1499 .context("X11: Failed to generate window ID")?;
1500
1501 let window = X11Window::new(
1502 handle,
1503 X11ClientStatePtr(Rc::downgrade(&self.0)),
1504 state.common.foreground_executor.clone(),
1505 &state.gpu_context,
1506 params,
1507 &state.xcb_connection,
1508 state.client_side_decorations_supported,
1509 state.x_root_index,
1510 x_window,
1511 &state.atoms,
1512 state.scale_factor,
1513 state.common.appearance,
1514 )?;
1515 check_reply(
1516 || "Failed to set XdndAware property",
1517 state.xcb_connection.change_property32(
1518 xproto::PropMode::REPLACE,
1519 x_window,
1520 state.atoms.XdndAware,
1521 state.atoms.XA_ATOM,
1522 &[5],
1523 ),
1524 )
1525 .log_err();
1526
1527 let window_ref = WindowRef {
1528 window: window.0.clone(),
1529 refresh_state: None,
1530 expose_event_received: false,
1531 last_visibility: Visibility::UNOBSCURED,
1532 is_mapped: false,
1533 };
1534
1535 state.windows.insert(x_window, window_ref);
1536 Ok(Box::new(window))
1537 }
1538
1539 fn set_cursor_style(&self, style: CursorStyle) {
1540 let mut state = self.0.borrow_mut();
1541 let Some(focused_window) = state.mouse_focused_window else {
1542 return;
1543 };
1544 let current_style = state
1545 .cursor_styles
1546 .get(&focused_window)
1547 .unwrap_or(&CursorStyle::Arrow);
1548 if *current_style == style {
1549 return;
1550 }
1551
1552 let Some(cursor) = state.get_cursor_icon(style) else {
1553 return;
1554 };
1555
1556 state.cursor_styles.insert(focused_window, style);
1557 state
1558 .xcb_connection
1559 .change_window_attributes(
1560 focused_window,
1561 &ChangeWindowAttributesAux {
1562 cursor: Some(cursor),
1563 ..Default::default()
1564 },
1565 )
1566 .anyhow()
1567 .and_then(|cookie| cookie.check().anyhow())
1568 .context("X11: Failed to set cursor style")
1569 .log_err();
1570 }
1571
1572 fn open_uri(&self, uri: &str) {
1573 #[cfg(any(feature = "wayland", feature = "x11"))]
1574 open_uri_internal(self.background_executor(), uri, None);
1575 }
1576
1577 fn reveal_path(&self, path: PathBuf) {
1578 #[cfg(any(feature = "x11", feature = "wayland"))]
1579 reveal_path_internal(self.background_executor(), path, None);
1580 }
1581
1582 fn write_to_primary(&self, item: crate::ClipboardItem) {
1583 let state = self.0.borrow_mut();
1584 state
1585 .clipboard
1586 .set_text(
1587 std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1588 clipboard::ClipboardKind::Primary,
1589 clipboard::WaitConfig::None,
1590 )
1591 .context("X11 Failed to write to clipboard (primary)")
1592 .log_with_level(log::Level::Debug);
1593 }
1594
1595 fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1596 let mut state = self.0.borrow_mut();
1597 state
1598 .clipboard
1599 .set_text(
1600 std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1601 clipboard::ClipboardKind::Clipboard,
1602 clipboard::WaitConfig::None,
1603 )
1604 .context("X11: Failed to write to clipboard (clipboard)")
1605 .log_with_level(log::Level::Debug);
1606 state.clipboard_item.replace(item);
1607 }
1608
1609 fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1610 let state = self.0.borrow_mut();
1611 return state
1612 .clipboard
1613 .get_any(clipboard::ClipboardKind::Primary)
1614 .context("X11: Failed to read from clipboard (primary)")
1615 .log_with_level(log::Level::Debug);
1616 }
1617
1618 fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1619 let state = self.0.borrow_mut();
1620 // if the last copy was from this app, return our cached item
1621 // which has metadata attached.
1622 if state
1623 .clipboard
1624 .is_owner(clipboard::ClipboardKind::Clipboard)
1625 {
1626 return state.clipboard_item.clone();
1627 }
1628 return state
1629 .clipboard
1630 .get_any(clipboard::ClipboardKind::Clipboard)
1631 .context("X11: Failed to read from clipboard (clipboard)")
1632 .log_with_level(log::Level::Debug);
1633 }
1634
1635 fn run(&self) {
1636 let Some(mut event_loop) = self
1637 .0
1638 .borrow_mut()
1639 .event_loop
1640 .take()
1641 .context("X11Client::run called but it's already running")
1642 .log_err()
1643 else {
1644 return;
1645 };
1646
1647 event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1648 }
1649
1650 fn active_window(&self) -> Option<AnyWindowHandle> {
1651 let state = self.0.borrow();
1652 state.keyboard_focused_window.and_then(|focused_window| {
1653 state
1654 .windows
1655 .get(&focused_window)
1656 .map(|window| window.handle())
1657 })
1658 }
1659
1660 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1661 let state = self.0.borrow();
1662 let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1663
1664 let reply = state
1665 .xcb_connection
1666 .get_property(
1667 false,
1668 root,
1669 state.atoms._NET_CLIENT_LIST_STACKING,
1670 xproto::AtomEnum::WINDOW,
1671 0,
1672 u32::MAX,
1673 )
1674 .ok()?
1675 .reply()
1676 .ok()?;
1677
1678 let window_ids = reply
1679 .value
1680 .chunks_exact(4)
1681 .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1682 .collect::<Vec<xproto::Window>>();
1683
1684 let mut handles = Vec::new();
1685
1686 // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1687 // a back-to-front order.
1688 // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1689 for window_ref in window_ids
1690 .iter()
1691 .rev()
1692 .filter_map(|&win| state.windows.get(&win))
1693 {
1694 if !window_ref.window.state.borrow().destroyed {
1695 handles.push(window_ref.handle());
1696 }
1697 }
1698
1699 Some(handles)
1700 }
1701}
1702
1703impl X11ClientState {
1704 fn has_xim(&self) -> bool {
1705 self.ximc.is_some() && self.xim_handler.is_some()
1706 }
1707
1708 fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1709 let ximc = self
1710 .ximc
1711 .take()
1712 .ok_or(anyhow!("bug: XIM connection not set"))
1713 .log_err()?;
1714 if let Some(xim_handler) = self.xim_handler.take() {
1715 Some((ximc, xim_handler))
1716 } else {
1717 self.ximc = Some(ximc);
1718 log::error!("bug: XIM handler not set");
1719 None
1720 }
1721 }
1722
1723 fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1724 self.ximc = Some(ximc);
1725 self.xim_handler = Some(xim_handler);
1726 }
1727
1728 fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1729 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1730 return;
1731 };
1732 let is_visible = window_ref.is_mapped
1733 && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1734 match (is_visible, window_ref.refresh_state.take()) {
1735 (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1736 | (false, refresh_state @ None)
1737 | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1738 window_ref.refresh_state = refresh_state;
1739 }
1740 (
1741 false,
1742 Some(RefreshState::PeriodicRefresh {
1743 refresh_rate,
1744 event_loop_token,
1745 }),
1746 ) => {
1747 self.loop_handle.remove(event_loop_token);
1748 window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1749 }
1750 (true, Some(RefreshState::Hidden { refresh_rate })) => {
1751 let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1752 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1753 return;
1754 };
1755 window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1756 refresh_rate,
1757 event_loop_token,
1758 });
1759 }
1760 (true, None) => {
1761 let Some(screen_resources) = get_reply(
1762 || "Failed to get screen resources",
1763 self.xcb_connection
1764 .randr_get_screen_resources_current(x_window),
1765 )
1766 .log_err() else {
1767 return;
1768 };
1769
1770 // Ideally this would be re-queried when the window changes screens, but there
1771 // doesn't seem to be an efficient / straightforward way to do this. Should also be
1772 // updated when screen configurations change.
1773 let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1774 let crtc_info = self
1775 .xcb_connection
1776 .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1777 .ok()?
1778 .reply()
1779 .ok()?;
1780
1781 screen_resources
1782 .modes
1783 .iter()
1784 .find(|m| m.id == crtc_info.mode)
1785 });
1786 let refresh_rate = match mode_info {
1787 Some(mode_info) => mode_refresh_rate(mode_info),
1788 None => {
1789 log::error!(
1790 "Failed to get screen mode info from xrandr, \
1791 defaulting to 60hz refresh rate."
1792 );
1793 Duration::from_micros(1_000_000 / 60)
1794 }
1795 };
1796
1797 let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1798 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1799 return;
1800 };
1801 window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1802 refresh_rate,
1803 event_loop_token,
1804 });
1805 }
1806 }
1807 }
1808
1809 #[must_use]
1810 fn start_refresh_loop(
1811 &self,
1812 x_window: xproto::Window,
1813 refresh_rate: Duration,
1814 ) -> RegistrationToken {
1815 self.loop_handle
1816 .insert_source(calloop::timer::Timer::immediate(), {
1817 move |mut instant, (), client| {
1818 let xcb_connection = {
1819 let mut state = client.0.borrow_mut();
1820 let xcb_connection = state.xcb_connection.clone();
1821 if let Some(window) = state.windows.get_mut(&x_window) {
1822 let expose_event_received = window.expose_event_received;
1823 window.expose_event_received = false;
1824 let window = window.window.clone();
1825 drop(state);
1826 window.refresh(RequestFrameOptions {
1827 require_presentation: expose_event_received,
1828 });
1829 }
1830 xcb_connection
1831 };
1832 client.process_x11_events(&xcb_connection).log_err();
1833
1834 // Take into account that some frames have been skipped
1835 let now = Instant::now();
1836 while instant < now {
1837 instant += refresh_rate;
1838 }
1839 calloop::timer::TimeoutAction::ToInstant(instant)
1840 }
1841 })
1842 .expect("Failed to initialize window refresh timer")
1843 }
1844
1845 fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1846 if let Some(cursor) = self.cursor_cache.get(&style) {
1847 return *cursor;
1848 }
1849
1850 let mut result;
1851 match style {
1852 CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1853 Ok(loaded_cursor) => result = Ok(loaded_cursor),
1854 Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1855 },
1856 _ => 'outer: {
1857 let mut errors = String::new();
1858 let cursor_icon_names = style.to_icon_names();
1859 for cursor_icon_name in cursor_icon_names {
1860 match self
1861 .cursor_handle
1862 .load_cursor(&self.xcb_connection, cursor_icon_name)
1863 {
1864 Ok(loaded_cursor) => {
1865 if loaded_cursor != x11rb::NONE {
1866 result = Ok(loaded_cursor);
1867 break 'outer;
1868 }
1869 }
1870 Err(err) => {
1871 errors.push_str(&err.to_string());
1872 errors.push('\n');
1873 }
1874 }
1875 }
1876 if errors.is_empty() {
1877 result = Err(anyhow!(
1878 "errors while loading cursor icons {:?}:\n{}",
1879 cursor_icon_names,
1880 errors
1881 ));
1882 } else {
1883 result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
1884 }
1885 }
1886 };
1887
1888 let cursor = match result {
1889 Ok(cursor) => Some(cursor),
1890 Err(err) => {
1891 match self
1892 .cursor_handle
1893 .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
1894 {
1895 Ok(default) => {
1896 log_cursor_icon_warning(err.context(format!(
1897 "X11: error loading cursor icon, falling back on default icon '{}'",
1898 DEFAULT_CURSOR_ICON_NAME
1899 )));
1900 Some(default)
1901 }
1902 Err(default_err) => {
1903 log_cursor_icon_warning(err.context(default_err).context(format!(
1904 "X11: error loading default cursor fallback '{}'",
1905 DEFAULT_CURSOR_ICON_NAME
1906 )));
1907 None
1908 }
1909 }
1910 }
1911 };
1912
1913 self.cursor_cache.insert(style, cursor);
1914 cursor
1915 }
1916}
1917
1918// Adapted from:
1919// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1920pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1921 if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1922 return Duration::from_millis(16);
1923 }
1924
1925 let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1926 let micros = 1_000_000_000 / millihertz;
1927 log::info!("Refreshing every {}ms", micros / 1_000);
1928 Duration::from_micros(micros)
1929}
1930
1931fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1932 value.integral as f32 + value.frac as f32 / u32::MAX as f32
1933}
1934
1935fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1936 // Method 1: Check for _NET_WM_CM_S{root}
1937 let atom_name = format!("_NET_WM_CM_S{}", root);
1938 let atom1 = get_reply(
1939 || format!("Failed to intern {atom_name}"),
1940 xcb_connection.intern_atom(false, atom_name.as_bytes()),
1941 );
1942 let method1 = match atom1.log_with_level(Level::Debug) {
1943 Some(reply) if reply.atom != x11rb::NONE => {
1944 let atom = reply.atom;
1945 get_reply(
1946 || format!("Failed to get {atom_name} owner"),
1947 xcb_connection.get_selection_owner(atom),
1948 )
1949 .map(|reply| reply.owner != 0)
1950 .log_with_level(Level::Debug)
1951 .unwrap_or(false)
1952 }
1953 _ => false,
1954 };
1955
1956 // Method 2: Check for _NET_WM_CM_OWNER
1957 let atom_name = "_NET_WM_CM_OWNER";
1958 let atom2 = get_reply(
1959 || format!("Failed to intern {atom_name}"),
1960 xcb_connection.intern_atom(false, atom_name.as_bytes()),
1961 );
1962 let method2 = match atom2.log_with_level(Level::Debug) {
1963 Some(reply) if reply.atom != x11rb::NONE => {
1964 let atom = reply.atom;
1965 get_reply(
1966 || format!("Failed to get {atom_name}"),
1967 xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1968 )
1969 .map(|reply| reply.value_len > 0)
1970 .unwrap_or(false)
1971 }
1972 _ => return false,
1973 };
1974
1975 // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1976 let atom_name = "_NET_SUPPORTING_WM_CHECK";
1977 let atom3 = get_reply(
1978 || format!("Failed to intern {atom_name}"),
1979 xcb_connection.intern_atom(false, atom_name.as_bytes()),
1980 );
1981 let method3 = match atom3.log_with_level(Level::Debug) {
1982 Some(reply) if reply.atom != x11rb::NONE => {
1983 let atom = reply.atom;
1984 get_reply(
1985 || format!("Failed to get {atom_name}"),
1986 xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1987 )
1988 .map(|reply| reply.value_len > 0)
1989 .unwrap_or(false)
1990 }
1991 _ => return false,
1992 };
1993
1994 log::debug!(
1995 "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1996 method1,
1997 method2,
1998 method3
1999 );
2000
2001 method1 || method2 || method3
2002}
2003
2004fn check_gtk_frame_extents_supported(
2005 xcb_connection: &XCBConnection,
2006 atoms: &XcbAtoms,
2007 root: xproto::Window,
2008) -> bool {
2009 let Some(supported_atoms) = get_reply(
2010 || "Failed to get _NET_SUPPORTED",
2011 xcb_connection.get_property(
2012 false,
2013 root,
2014 atoms._NET_SUPPORTED,
2015 xproto::AtomEnum::ATOM,
2016 0,
2017 1024,
2018 ),
2019 )
2020 .log_with_level(Level::Debug) else {
2021 return false;
2022 };
2023
2024 let supported_atom_ids: Vec<u32> = supported_atoms
2025 .value
2026 .chunks_exact(4)
2027 .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
2028 .collect();
2029
2030 supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
2031}
2032
2033fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2034 return atom == atoms.TEXT
2035 || atom == atoms.STRING
2036 || atom == atoms.UTF8_STRING
2037 || atom == atoms.TEXT_PLAIN
2038 || atom == atoms.TEXT_PLAIN_UTF8
2039 || atom == atoms.TextUriList;
2040}
2041
2042fn xdnd_get_supported_atom(
2043 xcb_connection: &XCBConnection,
2044 supported_atoms: &XcbAtoms,
2045 target: xproto::Window,
2046) -> u32 {
2047 if let Some(reply) = get_reply(
2048 || "Failed to get XDnD supported atoms",
2049 xcb_connection.get_property(
2050 false,
2051 target,
2052 supported_atoms.XdndTypeList,
2053 AtomEnum::ANY,
2054 0,
2055 1024,
2056 ),
2057 )
2058 .log_with_level(Level::Warn)
2059 {
2060 if let Some(atoms) = reply.value32() {
2061 for atom in atoms {
2062 if xdnd_is_atom_supported(atom, &supported_atoms) {
2063 return atom;
2064 }
2065 }
2066 }
2067 }
2068 return 0;
2069}
2070
2071fn xdnd_send_finished(
2072 xcb_connection: &XCBConnection,
2073 atoms: &XcbAtoms,
2074 source: xproto::Window,
2075 target: xproto::Window,
2076) {
2077 let message = ClientMessageEvent {
2078 format: 32,
2079 window: target,
2080 type_: atoms.XdndFinished,
2081 data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2082 sequence: 0,
2083 response_type: xproto::CLIENT_MESSAGE_EVENT,
2084 };
2085 check_reply(
2086 || "Failed to send XDnD finished event",
2087 xcb_connection.send_event(false, target, EventMask::default(), message),
2088 )
2089 .log_err();
2090}
2091
2092fn xdnd_send_status(
2093 xcb_connection: &XCBConnection,
2094 atoms: &XcbAtoms,
2095 source: xproto::Window,
2096 target: xproto::Window,
2097 action: u32,
2098) {
2099 let message = ClientMessageEvent {
2100 format: 32,
2101 window: target,
2102 type_: atoms.XdndStatus,
2103 data: ClientMessageData::from([source, 1, 0, 0, action]),
2104 sequence: 0,
2105 response_type: xproto::CLIENT_MESSAGE_EVENT,
2106 };
2107 check_reply(
2108 || "Failed to send XDnD status event",
2109 xcb_connection.send_event(false, target, EventMask::default(), message),
2110 )
2111 .log_err();
2112}
2113
2114/// Recomputes `pointer_device_states` by querying all pointer devices.
2115/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2116fn current_pointer_device_states(
2117 xcb_connection: &XCBConnection,
2118 scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2119) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2120 let devices_query_result = get_reply(
2121 || "Failed to query XInput devices",
2122 xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2123 )
2124 .log_err()?;
2125
2126 let mut pointer_device_states = BTreeMap::new();
2127 pointer_device_states.extend(
2128 devices_query_result
2129 .infos
2130 .iter()
2131 .filter(|info| is_pointer_device(info.type_))
2132 .filter_map(|info| {
2133 let scroll_data = info
2134 .classes
2135 .iter()
2136 .filter_map(|class| class.data.as_scroll())
2137 .map(|class| *class)
2138 .rev()
2139 .collect::<Vec<_>>();
2140 let old_state = scroll_values_to_preserve.get(&info.deviceid);
2141 let old_horizontal = old_state.map(|state| &state.horizontal);
2142 let old_vertical = old_state.map(|state| &state.vertical);
2143 let horizontal = scroll_data
2144 .iter()
2145 .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2146 .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2147 let vertical = scroll_data
2148 .iter()
2149 .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2150 .map(|data| scroll_data_to_axis_state(data, old_vertical));
2151 if horizontal.is_none() && vertical.is_none() {
2152 None
2153 } else {
2154 Some((
2155 info.deviceid,
2156 PointerDeviceState {
2157 horizontal: horizontal.unwrap_or_else(Default::default),
2158 vertical: vertical.unwrap_or_else(Default::default),
2159 },
2160 ))
2161 }
2162 }),
2163 );
2164 if pointer_device_states.is_empty() {
2165 log::error!("Found no xinput mouse pointers.");
2166 }
2167 return Some(pointer_device_states);
2168}
2169
2170/// Returns true if the device is a pointer device. Does not include pointer device groups.
2171fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2172 type_ == xinput::DeviceType::SLAVE_POINTER
2173}
2174
2175fn scroll_data_to_axis_state(
2176 data: &xinput::DeviceClassDataScroll,
2177 old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2178) -> ScrollAxisState {
2179 ScrollAxisState {
2180 valuator_number: Some(data.number),
2181 multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2182 scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2183 }
2184}
2185
2186fn reset_all_pointer_device_scroll_positions(
2187 pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2188) {
2189 pointer_device_states
2190 .iter_mut()
2191 .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2192}
2193
2194fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2195 pointer.horizontal.scroll_value = None;
2196 pointer.vertical.scroll_value = None;
2197}
2198
2199/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2200fn get_scroll_delta_and_update_state(
2201 pointer: &mut PointerDeviceState,
2202 event: &xinput::MotionEvent,
2203) -> Option<Point<f32>> {
2204 let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2205 let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2206 if delta_x.is_some() || delta_y.is_some() {
2207 Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2208 } else {
2209 None
2210 }
2211}
2212
2213fn get_axis_scroll_delta_and_update_state(
2214 event: &xinput::MotionEvent,
2215 axis: &mut ScrollAxisState,
2216) -> Option<f32> {
2217 let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2218 if let Some(axis_value) = event.axisvalues.get(axis_index) {
2219 let new_scroll = fp3232_to_f32(*axis_value);
2220 let delta_scroll = axis
2221 .scroll_value
2222 .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2223 axis.scroll_value = Some(new_scroll);
2224 delta_scroll
2225 } else {
2226 log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2227 None
2228 }
2229}
2230
2231fn make_scroll_wheel_event(
2232 position: Point<Pixels>,
2233 scroll_delta: Point<f32>,
2234 modifiers: Modifiers,
2235) -> crate::ScrollWheelEvent {
2236 // When shift is held down, vertical scrolling turns into horizontal scrolling.
2237 let delta = if modifiers.shift {
2238 Point {
2239 x: scroll_delta.y,
2240 y: 0.0,
2241 }
2242 } else {
2243 scroll_delta
2244 };
2245 crate::ScrollWheelEvent {
2246 position,
2247 delta: ScrollDelta::Lines(delta),
2248 modifiers,
2249 touch_phase: TouchPhase::default(),
2250 }
2251}
2252
2253fn create_invisible_cursor(
2254 connection: &XCBConnection,
2255) -> anyhow::Result<crate::platform::linux::x11::client::xproto::Cursor> {
2256 let empty_pixmap = connection.generate_id()?;
2257 let root = connection.setup().roots[0].root;
2258 connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2259
2260 let cursor = connection.generate_id()?;
2261 connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2262
2263 connection.free_pixmap(empty_pixmap)?;
2264
2265 connection.flush()?;
2266 Ok(cursor)
2267}