1use crate::{Capslock, xcb_flush};
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 http_client::Url;
19use log::Level;
20use smallvec::SmallVec;
21use util::ResultExt;
22
23use x11rb::{
24 connection::{Connection, RequestConnection},
25 cursor,
26 errors::ConnectionError,
27 protocol::randr::ConnectionExt as _,
28 protocol::xinput::ConnectionExt,
29 protocol::xkb::ConnectionExt as _,
30 protocol::xproto::{
31 AtomEnum, ChangeWindowAttributesAux, ClientMessageData, ClientMessageEvent,
32 ConnectionExt as _, EventMask, KeyPressEvent, Visibility,
33 },
34 protocol::{Event, randr, render, xinput, xkb, xproto},
35 resource_manager::Database,
36 wrapper::ConnectionExt as _,
37 xcb_ffi::XCBConnection,
38};
39use xim::{AttributeName, Client, InputStyle, x11rb::X11rbClient};
40use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
41use xkbcommon::xkb::{self as xkbc, LayoutIndex, ModMask, STATE_LAYOUT_EFFECTIVE};
42
43use super::{
44 ButtonOrScroll, ScrollDirection, X11Display, X11WindowStatePtr, XcbAtoms, XimCallbackEvent,
45 XimHandler, button_or_scroll_from_event_detail, check_reply,
46 clipboard::{self, Clipboard},
47 get_reply, get_valuator_axis_index, handle_connection_error, modifiers_from_state,
48 pressed_button_from_mask,
49};
50
51use crate::platform::{
52 LinuxCommon, PlatformWindow,
53 blade::BladeContext,
54 linux::{
55 DEFAULT_CURSOR_ICON_NAME, LinuxClient, get_xkb_compose_state, is_within_click_distance,
56 log_cursor_icon_warning, open_uri_internal,
57 platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES},
58 reveal_path_internal,
59 xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
60 },
61};
62use crate::{
63 AnyWindowHandle, Bounds, ClipboardItem, CursorStyle, DisplayId, FileDropEvent, Keystroke,
64 LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, Pixels, Platform,
65 PlatformDisplay, PlatformInput, PlatformKeyboardLayout, Point, RequestFrameOptions,
66 ScaledPixels, ScrollDelta, Size, TouchPhase, WindowParams, X11Window,
67 modifiers_from_xinput_info, point, px,
68};
69
70/// Value for DeviceId parameters which selects all devices.
71pub(crate) const XINPUT_ALL_DEVICES: xinput::DeviceId = 0;
72
73/// Value for DeviceId parameters which selects all device groups. Events that
74/// occur within the group are emitted by the group itself.
75///
76/// In XInput 2's interface, these are referred to as "master devices", but that
77/// terminology is both archaic and unclear.
78pub(crate) const XINPUT_ALL_DEVICE_GROUPS: xinput::DeviceId = 1;
79
80pub(crate) struct WindowRef {
81 window: X11WindowStatePtr,
82 refresh_state: Option<RefreshState>,
83 expose_event_received: bool,
84 last_visibility: Visibility,
85 is_mapped: bool,
86}
87
88impl WindowRef {
89 pub fn handle(&self) -> AnyWindowHandle {
90 self.window.state.borrow().handle
91 }
92}
93
94impl Deref for WindowRef {
95 type Target = X11WindowStatePtr;
96
97 fn deref(&self) -> &Self::Target {
98 &self.window
99 }
100}
101
102enum RefreshState {
103 Hidden {
104 refresh_rate: Duration,
105 },
106 PeriodicRefresh {
107 refresh_rate: Duration,
108 event_loop_token: RegistrationToken,
109 },
110}
111
112#[derive(Debug)]
113#[non_exhaustive]
114pub enum EventHandlerError {
115 XCBConnectionError(ConnectionError),
116 XIMClientError(xim::ClientError),
117}
118
119impl std::error::Error for EventHandlerError {}
120
121impl std::fmt::Display for EventHandlerError {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 match self {
124 EventHandlerError::XCBConnectionError(err) => err.fmt(f),
125 EventHandlerError::XIMClientError(err) => err.fmt(f),
126 }
127 }
128}
129
130impl From<ConnectionError> for EventHandlerError {
131 fn from(err: ConnectionError) -> Self {
132 EventHandlerError::XCBConnectionError(err)
133 }
134}
135
136impl From<xim::ClientError> for EventHandlerError {
137 fn from(err: xim::ClientError) -> Self {
138 EventHandlerError::XIMClientError(err)
139 }
140}
141
142#[derive(Debug, Default, Clone)]
143struct XKBStateNotiy {
144 depressed_layout: LayoutIndex,
145 latched_layout: LayoutIndex,
146 locked_layout: LayoutIndex,
147}
148
149#[derive(Debug, Default)]
150pub struct Xdnd {
151 other_window: xproto::Window,
152 drag_type: u32,
153 retrieved: bool,
154 position: Point<Pixels>,
155}
156
157#[derive(Debug)]
158struct PointerDeviceState {
159 horizontal: ScrollAxisState,
160 vertical: ScrollAxisState,
161}
162
163#[derive(Debug, Default)]
164struct ScrollAxisState {
165 /// Valuator number for looking up this axis's scroll value.
166 valuator_number: Option<u16>,
167 /// Conversion factor from scroll units to lines.
168 multiplier: f32,
169 /// Last scroll value for calculating scroll delta.
170 ///
171 /// This gets set to `None` whenever it might be invalid - when devices change or when window focus changes.
172 /// The logic errs on the side of invalidating this, since the consequence is just skipping the delta of one scroll event.
173 /// The consequence of not invalidating it can be large invalid deltas, which are much more user visible.
174 scroll_value: Option<f32>,
175}
176
177pub struct X11ClientState {
178 pub(crate) loop_handle: LoopHandle<'static, X11Client>,
179 pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
180
181 pub(crate) last_click: Instant,
182 pub(crate) last_mouse_button: Option<MouseButton>,
183 pub(crate) last_location: Point<Pixels>,
184 pub(crate) current_count: usize,
185
186 gpu_context: BladeContext,
187
188 pub(crate) scale_factor: f32,
189
190 xkb_context: xkbc::Context,
191 pub(crate) xcb_connection: Rc<XCBConnection>,
192 xkb_device_id: i32,
193 client_side_decorations_supported: bool,
194 pub(crate) x_root_index: usize,
195 pub(crate) _resource_database: Database,
196 pub(crate) atoms: XcbAtoms,
197 pub(crate) windows: HashMap<xproto::Window, WindowRef>,
198 pub(crate) mouse_focused_window: Option<xproto::Window>,
199 pub(crate) keyboard_focused_window: Option<xproto::Window>,
200 pub(crate) xkb: xkbc::State,
201 previous_xkb_state: XKBStateNotiy,
202 keyboard_layout: LinuxKeyboardLayout,
203 pub(crate) ximc: Option<X11rbClient<Rc<XCBConnection>>>,
204 pub(crate) xim_handler: Option<XimHandler>,
205 pub modifiers: Modifiers,
206 pub capslock: Capslock,
207 // TODO: Can the other updates to `modifiers` be removed so that this is unnecessary?
208 // capslock logic was done analog to modifiers
209 pub last_modifiers_changed_event: Modifiers,
210 pub last_capslock_changed_event: Capslock,
211
212 pub(crate) compose_state: Option<xkbc::compose::State>,
213 pub(crate) pre_edit_text: Option<String>,
214 pub(crate) composing: bool,
215 pub(crate) pre_key_char_down: Option<Keystroke>,
216 pub(crate) cursor_handle: cursor::Handle,
217 pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
218 pub(crate) cursor_cache: HashMap<CursorStyle, Option<xproto::Cursor>>,
219
220 pointer_device_states: BTreeMap<xinput::DeviceId, PointerDeviceState>,
221
222 pub(crate) common: LinuxCommon,
223 pub(crate) clipboard: Clipboard,
224 pub(crate) clipboard_item: Option<ClipboardItem>,
225 pub(crate) xdnd_state: Xdnd,
226}
227
228#[derive(Clone)]
229pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
230
231impl X11ClientStatePtr {
232 fn get_client(&self) -> Option<X11Client> {
233 self.0.upgrade().map(X11Client)
234 }
235
236 pub fn drop_window(&self, x_window: u32) {
237 let Some(client) = self.get_client() else {
238 return;
239 };
240 let mut state = client.0.borrow_mut();
241
242 if let Some(window_ref) = state.windows.remove(&x_window) {
243 match window_ref.refresh_state {
244 Some(RefreshState::PeriodicRefresh {
245 event_loop_token, ..
246 }) => {
247 state.loop_handle.remove(event_loop_token);
248 }
249 _ => {}
250 }
251 }
252 if state.mouse_focused_window == Some(x_window) {
253 state.mouse_focused_window = None;
254 }
255 if state.keyboard_focused_window == Some(x_window) {
256 state.keyboard_focused_window = None;
257 }
258 state.cursor_styles.remove(&x_window);
259
260 if state.windows.is_empty() {
261 state.common.signal.stop();
262 }
263 }
264
265 pub fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
266 let Some(client) = self.get_client() else {
267 return;
268 };
269 let mut state = client.0.borrow_mut();
270 if state.composing || state.ximc.is_none() {
271 return;
272 }
273
274 let Some(mut ximc) = state.ximc.take() else {
275 log::error!("bug: xim connection not set");
276 return;
277 };
278 let Some(xim_handler) = state.xim_handler.take() else {
279 log::error!("bug: xim handler not set");
280 state.ximc = Some(ximc);
281 return;
282 };
283 let ic_attributes = ximc
284 .build_ic_attributes()
285 .push(
286 xim::AttributeName::InputStyle,
287 xim::InputStyle::PREEDIT_CALLBACKS,
288 )
289 .push(xim::AttributeName::ClientWindow, xim_handler.window)
290 .push(xim::AttributeName::FocusWindow, xim_handler.window)
291 .nested_list(xim::AttributeName::PreeditAttributes, |b| {
292 b.push(
293 xim::AttributeName::SpotLocation,
294 xim::Point {
295 x: u32::from(bounds.origin.x + bounds.size.width) as i16,
296 y: u32::from(bounds.origin.y + bounds.size.height) as i16,
297 },
298 );
299 })
300 .build();
301 let _ = ximc
302 .set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
303 .log_err();
304 state.ximc = Some(ximc);
305 state.xim_handler = Some(xim_handler);
306 }
307}
308
309#[derive(Clone)]
310pub(crate) struct X11Client(Rc<RefCell<X11ClientState>>);
311
312impl X11Client {
313 pub(crate) fn new() -> anyhow::Result<Self> {
314 let event_loop = EventLoop::try_new()?;
315
316 let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
317
318 let handle = event_loop.handle();
319
320 handle
321 .insert_source(main_receiver, {
322 let handle = handle.clone();
323 move |event, _, _: &mut X11Client| {
324 if let calloop::channel::Event::Msg(runnable) = event {
325 // Insert the runnables as idle callbacks, so we make sure that user-input and X11
326 // events have higher priority and runnables are only worked off after the event
327 // callbacks.
328 handle.insert_idle(|_| {
329 runnable.run();
330 });
331 }
332 }
333 })
334 .map_err(|err| {
335 anyhow!("Failed to initialize event loop handling of foreground tasks: {err:?}")
336 })?;
337
338 let (xcb_connection, x_root_index) = XCBConnection::connect(None)?;
339 xcb_connection.prefetch_extension_information(xkb::X11_EXTENSION_NAME)?;
340 xcb_connection.prefetch_extension_information(randr::X11_EXTENSION_NAME)?;
341 xcb_connection.prefetch_extension_information(render::X11_EXTENSION_NAME)?;
342 xcb_connection.prefetch_extension_information(xinput::X11_EXTENSION_NAME)?;
343
344 // Announce to X server that XInput up to 2.1 is supported. To increase this to 2.2 and
345 // beyond, support for touch events would need to be added.
346 let xinput_version = get_reply(
347 || "XInput XiQueryVersion failed",
348 xcb_connection.xinput_xi_query_version(2, 1),
349 )?;
350 assert!(
351 xinput_version.major_version >= 2,
352 "XInput version >= 2 required."
353 );
354
355 let pointer_device_states =
356 current_pointer_device_states(&xcb_connection, &BTreeMap::new()).unwrap_or_default();
357
358 let atoms = XcbAtoms::new(&xcb_connection)
359 .context("Failed to get XCB atoms")?
360 .reply()
361 .context("Failed to get XCB atoms")?;
362
363 let root = xcb_connection.setup().roots[0].root;
364 let compositor_present = check_compositor_present(&xcb_connection, root);
365 let gtk_frame_extents_supported =
366 check_gtk_frame_extents_supported(&xcb_connection, &atoms, root);
367 let client_side_decorations_supported = compositor_present && gtk_frame_extents_supported;
368 log::info!(
369 "x11: compositor present: {}, gtk_frame_extents_supported: {}",
370 compositor_present,
371 gtk_frame_extents_supported
372 );
373
374 let xkb = get_reply(
375 || "Failed to initialize XKB extension",
376 xcb_connection
377 .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION),
378 )?;
379 assert!(xkb.supported);
380
381 let events = xkb::EventType::STATE_NOTIFY
382 | xkb::EventType::MAP_NOTIFY
383 | xkb::EventType::NEW_KEYBOARD_NOTIFY;
384 let map_notify_parts = xkb::MapPart::KEY_TYPES
385 | xkb::MapPart::KEY_SYMS
386 | xkb::MapPart::MODIFIER_MAP
387 | xkb::MapPart::EXPLICIT_COMPONENTS
388 | xkb::MapPart::KEY_ACTIONS
389 | xkb::MapPart::KEY_BEHAVIORS
390 | xkb::MapPart::VIRTUAL_MODS
391 | xkb::MapPart::VIRTUAL_MOD_MAP;
392 check_reply(
393 || "Failed to select XKB events",
394 xcb_connection.xkb_select_events(
395 xkb::ID::USE_CORE_KBD.into(),
396 0u8.into(),
397 events,
398 map_notify_parts,
399 map_notify_parts,
400 &xkb::SelectEventsAux::new(),
401 ),
402 )?;
403
404 let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
405 let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
406 let xkb_state = {
407 let xkb_keymap = xkbc::x11::keymap_new_from_device(
408 &xkb_context,
409 &xcb_connection,
410 xkb_device_id,
411 xkbc::KEYMAP_COMPILE_NO_FLAGS,
412 );
413 xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
414 };
415 let compose_state = get_xkb_compose_state(&xkb_context);
416 let layout_idx = xkb_state.serialize_layout(STATE_LAYOUT_EFFECTIVE);
417 let layout_name = xkb_state
418 .get_keymap()
419 .layout_get_name(layout_idx)
420 .to_string();
421 let keyboard_layout = LinuxKeyboardLayout::new(layout_name.into());
422
423 let gpu_context = BladeContext::new().context("Unable to init GPU context")?;
424
425 let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection)
426 .context("Failed to create resource database")?;
427 let scale_factor = resource_database
428 .get_value("Xft.dpi", "Xft.dpi")
429 .ok()
430 .flatten()
431 .map(|dpi: f32| dpi / 96.0)
432 .unwrap_or(1.0);
433 let cursor_handle = cursor::Handle::new(&xcb_connection, x_root_index, &resource_database)
434 .context("Failed to initialize cursor theme handler")?
435 .reply()
436 .context("Failed to initialize cursor theme handler")?;
437
438 let clipboard = Clipboard::new().context("Failed to initialize clipboard")?;
439
440 let xcb_connection = Rc::new(xcb_connection);
441
442 let ximc = X11rbClient::init(Rc::clone(&xcb_connection), x_root_index, None).ok();
443 let xim_handler = if ximc.is_some() {
444 Some(XimHandler::new())
445 } else {
446 None
447 };
448
449 // Safety: Safe if xcb::Connection always returns a valid fd
450 let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
451
452 handle
453 .insert_source(
454 Generic::new_with_error::<EventHandlerError>(
455 fd,
456 calloop::Interest::READ,
457 calloop::Mode::Level,
458 ),
459 {
460 let xcb_connection = xcb_connection.clone();
461 move |_readiness, _, client| {
462 client.process_x11_events(&xcb_connection)?;
463 Ok(calloop::PostAction::Continue)
464 }
465 },
466 )
467 .map_err(|err| anyhow!("Failed to initialize X11 event source: {err:?}"))?;
468
469 handle
470 .insert_source(XDPEventSource::new(&common.background_executor), {
471 move |event, _, client| match event {
472 XDPEvent::WindowAppearance(appearance) => {
473 client.with_common(|common| common.appearance = appearance);
474 for (_, window) in &mut client.0.borrow_mut().windows {
475 window.window.set_appearance(appearance);
476 }
477 }
478 XDPEvent::CursorTheme(_) | XDPEvent::CursorSize(_) => {
479 // noop, X11 manages this for us.
480 }
481 }
482 })
483 .map_err(|err| anyhow!("Failed to initialize XDP event source: {err:?}"))?;
484
485 xcb_flush(&xcb_connection);
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 println!("X11 Before {:#?}", keystroke);
1046 if let Some(mut compose_state) = state.compose_state.take() {
1047 compose_state.feed(keysym);
1048 match compose_state.status() {
1049 xkbc::Status::Composed => {
1050 state.pre_edit_text.take();
1051 keystroke.key_char = compose_state.utf8();
1052 if let Some(keysym) = compose_state.keysym() {
1053 keystroke.key = xkbc::keysym_get_name(keysym);
1054 }
1055 }
1056 xkbc::Status::Composing => {
1057 keystroke.key_char = None;
1058 state.pre_edit_text = compose_state
1059 .utf8()
1060 .or(crate::Keystroke::underlying_dead_key(keysym));
1061 let pre_edit =
1062 state.pre_edit_text.clone().unwrap_or(String::default());
1063 drop(state);
1064 window.handle_ime_preedit(pre_edit);
1065 state = self.0.borrow_mut();
1066 }
1067 xkbc::Status::Cancelled => {
1068 let pre_edit = state.pre_edit_text.take();
1069 drop(state);
1070 if let Some(pre_edit) = pre_edit {
1071 window.handle_ime_commit(pre_edit);
1072 }
1073 if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
1074 window.handle_ime_preedit(current_key);
1075 }
1076 state = self.0.borrow_mut();
1077 compose_state.feed(keysym);
1078 }
1079 _ => {}
1080 }
1081 state.compose_state = Some(compose_state);
1082 }
1083 keystroke
1084 };
1085 drop(state);
1086 println!("X11 Key pressed: {:#?}", keystroke);
1087 window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1088 keystroke,
1089 is_held: false,
1090 }));
1091 }
1092 Event::KeyRelease(event) => {
1093 let window = self.get_window(event.event)?;
1094 let mut state = self.0.borrow_mut();
1095
1096 let modifiers = modifiers_from_state(event.state);
1097 state.modifiers = modifiers;
1098
1099 let keystroke = {
1100 let code = event.detail.into();
1101 let xkb_state = state.previous_xkb_state.clone();
1102 state.xkb.update_mask(
1103 event.state.bits() as ModMask,
1104 0,
1105 0,
1106 xkb_state.depressed_layout,
1107 xkb_state.latched_layout,
1108 xkb_state.locked_layout,
1109 );
1110 let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
1111 let keysym = state.xkb.key_get_one_sym(code);
1112 if keysym.is_modifier_key() {
1113 return Some(());
1114 }
1115 keystroke
1116 };
1117 drop(state);
1118 window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
1119 }
1120 Event::XinputButtonPress(event) => {
1121 let window = self.get_window(event.event)?;
1122 let mut state = self.0.borrow_mut();
1123
1124 let modifiers = modifiers_from_xinput_info(event.mods);
1125 state.modifiers = modifiers;
1126
1127 let position = point(
1128 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1129 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1130 );
1131
1132 if state.composing && state.ximc.is_some() {
1133 drop(state);
1134 self.reset_ime();
1135 window.handle_ime_unmark();
1136 state = self.0.borrow_mut();
1137 } else if let Some(text) = state.pre_edit_text.take() {
1138 if let Some(compose_state) = state.compose_state.as_mut() {
1139 compose_state.reset();
1140 }
1141 drop(state);
1142 window.handle_ime_commit(text);
1143 state = self.0.borrow_mut();
1144 }
1145 match button_or_scroll_from_event_detail(event.detail) {
1146 Some(ButtonOrScroll::Button(button)) => {
1147 let click_elapsed = state.last_click.elapsed();
1148 if click_elapsed < DOUBLE_CLICK_INTERVAL
1149 && state
1150 .last_mouse_button
1151 .is_some_and(|prev_button| prev_button == button)
1152 && is_within_click_distance(state.last_location, position)
1153 {
1154 state.current_count += 1;
1155 } else {
1156 state.current_count = 1;
1157 }
1158
1159 state.last_click = Instant::now();
1160 state.last_mouse_button = Some(button);
1161 state.last_location = position;
1162 let current_count = state.current_count;
1163
1164 drop(state);
1165 window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
1166 button,
1167 position,
1168 modifiers,
1169 click_count: current_count,
1170 first_mouse: false,
1171 }));
1172 }
1173 Some(ButtonOrScroll::Scroll(direction)) => {
1174 drop(state);
1175 // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1176 // Since handling those events does the scrolling, they are skipped here.
1177 if !event
1178 .flags
1179 .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1180 {
1181 let scroll_delta = match direction {
1182 ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1183 ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1184 ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1185 ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1186 };
1187 window.handle_input(PlatformInput::ScrollWheel(
1188 make_scroll_wheel_event(position, scroll_delta, modifiers),
1189 ));
1190 }
1191 }
1192 None => {
1193 log::error!("Unknown x11 button: {}", event.detail);
1194 }
1195 }
1196 }
1197 Event::XinputButtonRelease(event) => {
1198 let window = self.get_window(event.event)?;
1199 let mut state = self.0.borrow_mut();
1200 let modifiers = modifiers_from_xinput_info(event.mods);
1201 state.modifiers = modifiers;
1202
1203 let position = point(
1204 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1205 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1206 );
1207 match button_or_scroll_from_event_detail(event.detail) {
1208 Some(ButtonOrScroll::Button(button)) => {
1209 let click_count = state.current_count;
1210 drop(state);
1211 window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
1212 button,
1213 position,
1214 modifiers,
1215 click_count,
1216 }));
1217 }
1218 Some(ButtonOrScroll::Scroll(_)) => {}
1219 None => {}
1220 }
1221 }
1222 Event::XinputMotion(event) => {
1223 let window = self.get_window(event.event)?;
1224 let mut state = self.0.borrow_mut();
1225 let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1226 let position = point(
1227 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1228 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1229 );
1230 let modifiers = modifiers_from_xinput_info(event.mods);
1231 state.modifiers = modifiers;
1232 drop(state);
1233
1234 if event.valuator_mask[0] & 3 != 0 {
1235 window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
1236 position,
1237 pressed_button,
1238 modifiers,
1239 }));
1240 }
1241
1242 state = self.0.borrow_mut();
1243 if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1244 let scroll_delta = get_scroll_delta_and_update_state(&mut pointer, &event);
1245 drop(state);
1246 if let Some(scroll_delta) = scroll_delta {
1247 window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1248 position,
1249 scroll_delta,
1250 modifiers,
1251 )));
1252 }
1253 }
1254 }
1255 Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1256 let window = self.get_window(event.event)?;
1257 window.set_hovered(true);
1258 let mut state = self.0.borrow_mut();
1259 state.mouse_focused_window = Some(event.event);
1260 }
1261 Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1262 let mut state = self.0.borrow_mut();
1263
1264 // 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)
1265 reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1266 state.mouse_focused_window = None;
1267 let pressed_button = pressed_button_from_mask(event.buttons[0]);
1268 let position = point(
1269 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1270 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1271 );
1272 let modifiers = modifiers_from_xinput_info(event.mods);
1273 state.modifiers = modifiers;
1274 drop(state);
1275
1276 let window = self.get_window(event.event)?;
1277 window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
1278 pressed_button,
1279 position,
1280 modifiers,
1281 }));
1282 window.set_hovered(false);
1283 }
1284 Event::XinputHierarchy(event) => {
1285 let mut state = self.0.borrow_mut();
1286 // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1287 // Any change to a device invalidates its scroll values.
1288 for info in event.infos {
1289 if is_pointer_device(info.type_) {
1290 state.pointer_device_states.remove(&info.deviceid);
1291 }
1292 }
1293 if let Some(pointer_device_states) = current_pointer_device_states(
1294 &state.xcb_connection,
1295 &state.pointer_device_states,
1296 ) {
1297 state.pointer_device_states = pointer_device_states;
1298 }
1299 }
1300 Event::XinputDeviceChanged(event) => {
1301 let mut state = self.0.borrow_mut();
1302 if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1303 reset_pointer_device_scroll_positions(&mut pointer);
1304 }
1305 }
1306 _ => {}
1307 };
1308
1309 Some(())
1310 }
1311
1312 fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1313 match event {
1314 XimCallbackEvent::XimXEvent(event) => {
1315 self.handle_event(event);
1316 }
1317 XimCallbackEvent::XimCommitEvent(window, text) => {
1318 self.xim_handle_commit(window, text);
1319 }
1320 XimCallbackEvent::XimPreeditEvent(window, text) => {
1321 self.xim_handle_preedit(window, text);
1322 }
1323 };
1324 }
1325
1326 fn xim_handle_event(&self, event: Event) -> Option<()> {
1327 match event {
1328 Event::KeyPress(event) | Event::KeyRelease(event) => {
1329 let mut state = self.0.borrow_mut();
1330 state.pre_key_char_down = Some(Keystroke::from_xkb(
1331 &state.xkb,
1332 state.modifiers,
1333 event.detail.into(),
1334 ));
1335 let (mut ximc, mut xim_handler) = state.take_xim()?;
1336 drop(state);
1337 xim_handler.window = event.event;
1338 ximc.forward_event(
1339 xim_handler.im_id,
1340 xim_handler.ic_id,
1341 xim::ForwardEventFlag::empty(),
1342 &event,
1343 )
1344 .context("X11: Failed to forward XIM event")
1345 .log_err();
1346 let mut state = self.0.borrow_mut();
1347 state.restore_xim(ximc, xim_handler);
1348 drop(state);
1349 }
1350 event => {
1351 self.handle_event(event);
1352 }
1353 }
1354 Some(())
1355 }
1356
1357 fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1358 let Some(window) = self.get_window(window) else {
1359 log::error!("bug: Failed to get window for XIM commit");
1360 return None;
1361 };
1362 let mut state = self.0.borrow_mut();
1363 let keystroke = state.pre_key_char_down.take();
1364 state.composing = false;
1365 drop(state);
1366 if let Some(mut keystroke) = keystroke {
1367 keystroke.key_char = Some(text.clone());
1368 window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1369 keystroke,
1370 is_held: false,
1371 }));
1372 }
1373
1374 Some(())
1375 }
1376
1377 fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1378 let Some(window) = self.get_window(window) else {
1379 log::error!("bug: Failed to get window for XIM preedit");
1380 return None;
1381 };
1382
1383 let mut state = self.0.borrow_mut();
1384 let (mut ximc, mut xim_handler) = state.take_xim()?;
1385 state.composing = !text.is_empty();
1386 drop(state);
1387 window.handle_ime_preedit(text);
1388
1389 if let Some(area) = window.get_ime_area() {
1390 let ic_attributes = ximc
1391 .build_ic_attributes()
1392 .push(
1393 xim::AttributeName::InputStyle,
1394 xim::InputStyle::PREEDIT_CALLBACKS,
1395 )
1396 .push(xim::AttributeName::ClientWindow, xim_handler.window)
1397 .push(xim::AttributeName::FocusWindow, xim_handler.window)
1398 .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1399 b.push(
1400 xim::AttributeName::SpotLocation,
1401 xim::Point {
1402 x: u32::from(area.origin.x + area.size.width) as i16,
1403 y: u32::from(area.origin.y + area.size.height) as i16,
1404 },
1405 );
1406 })
1407 .build();
1408 ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1409 .ok();
1410 }
1411 let mut state = self.0.borrow_mut();
1412 state.restore_xim(ximc, xim_handler);
1413 drop(state);
1414 Some(())
1415 }
1416
1417 fn handle_keyboard_layout_change(&self) {
1418 let mut state = self.0.borrow_mut();
1419 let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1420 let keymap = state.xkb.get_keymap();
1421 let layout_name = keymap.layout_get_name(layout_idx);
1422 if layout_name != state.keyboard_layout.name() {
1423 state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1424 if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1425 drop(state);
1426 callback();
1427 state = self.0.borrow_mut();
1428 state.common.callbacks.keyboard_layout_change = Some(callback);
1429 }
1430 }
1431 }
1432}
1433
1434impl LinuxClient for X11Client {
1435 fn compositor_name(&self) -> &'static str {
1436 "X11"
1437 }
1438
1439 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1440 f(&mut self.0.borrow_mut().common)
1441 }
1442
1443 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1444 let state = self.0.borrow();
1445 Box::new(state.keyboard_layout.clone())
1446 }
1447
1448 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1449 let state = self.0.borrow();
1450 let setup = state.xcb_connection.setup();
1451 setup
1452 .roots
1453 .iter()
1454 .enumerate()
1455 .filter_map(|(root_id, _)| {
1456 Some(Rc::new(
1457 X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1458 ) as Rc<dyn PlatformDisplay>)
1459 })
1460 .collect()
1461 }
1462
1463 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1464 let state = self.0.borrow();
1465 X11Display::new(
1466 &state.xcb_connection,
1467 state.scale_factor,
1468 state.x_root_index,
1469 )
1470 .log_err()
1471 .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1472 }
1473
1474 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1475 let state = self.0.borrow();
1476
1477 Some(Rc::new(
1478 X11Display::new(&state.xcb_connection, state.scale_factor, id.0 as usize).ok()?,
1479 ))
1480 }
1481
1482 #[cfg(feature = "screen-capture")]
1483 fn is_screen_capture_supported(&self) -> bool {
1484 true
1485 }
1486
1487 #[cfg(feature = "screen-capture")]
1488 fn screen_capture_sources(
1489 &self,
1490 ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Box<dyn crate::ScreenCaptureSource>>>>
1491 {
1492 crate::platform::scap_screen_capture::scap_screen_sources(
1493 &self.0.borrow().common.foreground_executor,
1494 )
1495 }
1496
1497 fn open_window(
1498 &self,
1499 handle: AnyWindowHandle,
1500 params: WindowParams,
1501 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1502 let mut state = self.0.borrow_mut();
1503 let x_window = state
1504 .xcb_connection
1505 .generate_id()
1506 .context("X11: Failed to generate window ID")?;
1507
1508 let window = X11Window::new(
1509 handle,
1510 X11ClientStatePtr(Rc::downgrade(&self.0)),
1511 state.common.foreground_executor.clone(),
1512 &state.gpu_context,
1513 params,
1514 &state.xcb_connection,
1515 state.client_side_decorations_supported,
1516 state.x_root_index,
1517 x_window,
1518 &state.atoms,
1519 state.scale_factor,
1520 state.common.appearance,
1521 )?;
1522 check_reply(
1523 || "Failed to set XdndAware property",
1524 state.xcb_connection.change_property32(
1525 xproto::PropMode::REPLACE,
1526 x_window,
1527 state.atoms.XdndAware,
1528 state.atoms.XA_ATOM,
1529 &[5],
1530 ),
1531 )
1532 .log_err();
1533 xcb_flush(&state.xcb_connection);
1534
1535 let window_ref = WindowRef {
1536 window: window.0.clone(),
1537 refresh_state: None,
1538 expose_event_received: false,
1539 last_visibility: Visibility::UNOBSCURED,
1540 is_mapped: false,
1541 };
1542
1543 state.windows.insert(x_window, window_ref);
1544 Ok(Box::new(window))
1545 }
1546
1547 fn set_cursor_style(&self, style: CursorStyle) {
1548 let mut state = self.0.borrow_mut();
1549 let Some(focused_window) = state.mouse_focused_window else {
1550 return;
1551 };
1552 let current_style = state
1553 .cursor_styles
1554 .get(&focused_window)
1555 .unwrap_or(&CursorStyle::Arrow);
1556 if *current_style == style {
1557 return;
1558 }
1559
1560 let Some(cursor) = state.get_cursor_icon(style) else {
1561 return;
1562 };
1563
1564 state.cursor_styles.insert(focused_window, style);
1565 check_reply(
1566 || "Failed to set cursor style",
1567 state.xcb_connection.change_window_attributes(
1568 focused_window,
1569 &ChangeWindowAttributesAux {
1570 cursor: Some(cursor),
1571 ..Default::default()
1572 },
1573 ),
1574 )
1575 .log_err();
1576 state.xcb_connection.flush().log_err();
1577 }
1578
1579 fn open_uri(&self, uri: &str) {
1580 #[cfg(any(feature = "wayland", feature = "x11"))]
1581 open_uri_internal(self.background_executor(), uri, None);
1582 }
1583
1584 fn reveal_path(&self, path: PathBuf) {
1585 #[cfg(any(feature = "x11", feature = "wayland"))]
1586 reveal_path_internal(self.background_executor(), path, None);
1587 }
1588
1589 fn write_to_primary(&self, item: crate::ClipboardItem) {
1590 let state = self.0.borrow_mut();
1591 state
1592 .clipboard
1593 .set_text(
1594 std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1595 clipboard::ClipboardKind::Primary,
1596 clipboard::WaitConfig::None,
1597 )
1598 .context("X11 Failed to write to clipboard (primary)")
1599 .log_with_level(log::Level::Debug);
1600 }
1601
1602 fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1603 let mut state = self.0.borrow_mut();
1604 state
1605 .clipboard
1606 .set_text(
1607 std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1608 clipboard::ClipboardKind::Clipboard,
1609 clipboard::WaitConfig::None,
1610 )
1611 .context("X11: Failed to write to clipboard (clipboard)")
1612 .log_with_level(log::Level::Debug);
1613 state.clipboard_item.replace(item);
1614 }
1615
1616 fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1617 let state = self.0.borrow_mut();
1618 return state
1619 .clipboard
1620 .get_any(clipboard::ClipboardKind::Primary)
1621 .context("X11: Failed to read from clipboard (primary)")
1622 .log_with_level(log::Level::Debug);
1623 }
1624
1625 fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1626 let state = self.0.borrow_mut();
1627 // if the last copy was from this app, return our cached item
1628 // which has metadata attached.
1629 if state
1630 .clipboard
1631 .is_owner(clipboard::ClipboardKind::Clipboard)
1632 {
1633 return state.clipboard_item.clone();
1634 }
1635 return state
1636 .clipboard
1637 .get_any(clipboard::ClipboardKind::Clipboard)
1638 .context("X11: Failed to read from clipboard (clipboard)")
1639 .log_with_level(log::Level::Debug);
1640 }
1641
1642 fn run(&self) {
1643 let Some(mut event_loop) = self
1644 .0
1645 .borrow_mut()
1646 .event_loop
1647 .take()
1648 .context("X11Client::run called but it's already running")
1649 .log_err()
1650 else {
1651 return;
1652 };
1653
1654 event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1655 }
1656
1657 fn active_window(&self) -> Option<AnyWindowHandle> {
1658 let state = self.0.borrow();
1659 state.keyboard_focused_window.and_then(|focused_window| {
1660 state
1661 .windows
1662 .get(&focused_window)
1663 .map(|window| window.handle())
1664 })
1665 }
1666
1667 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1668 let state = self.0.borrow();
1669 let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1670
1671 let reply = state
1672 .xcb_connection
1673 .get_property(
1674 false,
1675 root,
1676 state.atoms._NET_CLIENT_LIST_STACKING,
1677 xproto::AtomEnum::WINDOW,
1678 0,
1679 u32::MAX,
1680 )
1681 .ok()?
1682 .reply()
1683 .ok()?;
1684
1685 let window_ids = reply
1686 .value
1687 .chunks_exact(4)
1688 .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1689 .collect::<Vec<xproto::Window>>();
1690
1691 let mut handles = Vec::new();
1692
1693 // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1694 // a back-to-front order.
1695 // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1696 for window_ref in window_ids
1697 .iter()
1698 .rev()
1699 .filter_map(|&win| state.windows.get(&win))
1700 {
1701 if !window_ref.window.state.borrow().destroyed {
1702 handles.push(window_ref.handle());
1703 }
1704 }
1705
1706 Some(handles)
1707 }
1708}
1709
1710impl X11ClientState {
1711 fn has_xim(&self) -> bool {
1712 self.ximc.is_some() && self.xim_handler.is_some()
1713 }
1714
1715 fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1716 let ximc = self
1717 .ximc
1718 .take()
1719 .ok_or(anyhow!("bug: XIM connection not set"))
1720 .log_err()?;
1721 if let Some(xim_handler) = self.xim_handler.take() {
1722 Some((ximc, xim_handler))
1723 } else {
1724 self.ximc = Some(ximc);
1725 log::error!("bug: XIM handler not set");
1726 None
1727 }
1728 }
1729
1730 fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1731 self.ximc = Some(ximc);
1732 self.xim_handler = Some(xim_handler);
1733 }
1734
1735 fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1736 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1737 return;
1738 };
1739 let is_visible = window_ref.is_mapped
1740 && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1741 match (is_visible, window_ref.refresh_state.take()) {
1742 (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1743 | (false, refresh_state @ None)
1744 | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1745 window_ref.refresh_state = refresh_state;
1746 }
1747 (
1748 false,
1749 Some(RefreshState::PeriodicRefresh {
1750 refresh_rate,
1751 event_loop_token,
1752 }),
1753 ) => {
1754 self.loop_handle.remove(event_loop_token);
1755 window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1756 }
1757 (true, Some(RefreshState::Hidden { refresh_rate })) => {
1758 let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1759 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1760 return;
1761 };
1762 window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1763 refresh_rate,
1764 event_loop_token,
1765 });
1766 }
1767 (true, None) => {
1768 let Some(screen_resources) = get_reply(
1769 || "Failed to get screen resources",
1770 self.xcb_connection
1771 .randr_get_screen_resources_current(x_window),
1772 )
1773 .log_err() else {
1774 return;
1775 };
1776
1777 // Ideally this would be re-queried when the window changes screens, but there
1778 // doesn't seem to be an efficient / straightforward way to do this. Should also be
1779 // updated when screen configurations change.
1780 let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1781 let crtc_info = self
1782 .xcb_connection
1783 .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1784 .ok()?
1785 .reply()
1786 .ok()?;
1787
1788 screen_resources
1789 .modes
1790 .iter()
1791 .find(|m| m.id == crtc_info.mode)
1792 });
1793 let refresh_rate = match mode_info {
1794 Some(mode_info) => mode_refresh_rate(mode_info),
1795 None => {
1796 log::error!(
1797 "Failed to get screen mode info from xrandr, \
1798 defaulting to 60hz refresh rate."
1799 );
1800 Duration::from_micros(1_000_000 / 60)
1801 }
1802 };
1803
1804 let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1805 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1806 return;
1807 };
1808 window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1809 refresh_rate,
1810 event_loop_token,
1811 });
1812 }
1813 }
1814 }
1815
1816 #[must_use]
1817 fn start_refresh_loop(
1818 &self,
1819 x_window: xproto::Window,
1820 refresh_rate: Duration,
1821 ) -> RegistrationToken {
1822 self.loop_handle
1823 .insert_source(calloop::timer::Timer::immediate(), {
1824 move |mut instant, (), client| {
1825 let xcb_connection = {
1826 let mut state = client.0.borrow_mut();
1827 let xcb_connection = state.xcb_connection.clone();
1828 if let Some(window) = state.windows.get_mut(&x_window) {
1829 let expose_event_received = window.expose_event_received;
1830 window.expose_event_received = false;
1831 let window = window.window.clone();
1832 drop(state);
1833 window.refresh(RequestFrameOptions {
1834 require_presentation: expose_event_received,
1835 });
1836 }
1837 xcb_connection
1838 };
1839 client.process_x11_events(&xcb_connection).log_err();
1840
1841 // Take into account that some frames have been skipped
1842 let now = Instant::now();
1843 while instant < now {
1844 instant += refresh_rate;
1845 }
1846 calloop::timer::TimeoutAction::ToInstant(instant)
1847 }
1848 })
1849 .expect("Failed to initialize window refresh timer")
1850 }
1851
1852 fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1853 if let Some(cursor) = self.cursor_cache.get(&style) {
1854 return *cursor;
1855 }
1856
1857 let mut result;
1858 match style {
1859 CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1860 Ok(loaded_cursor) => result = Ok(loaded_cursor),
1861 Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1862 },
1863 _ => 'outer: {
1864 let mut errors = String::new();
1865 let cursor_icon_names = style.to_icon_names();
1866 for cursor_icon_name in cursor_icon_names {
1867 match self
1868 .cursor_handle
1869 .load_cursor(&self.xcb_connection, cursor_icon_name)
1870 {
1871 Ok(loaded_cursor) => {
1872 if loaded_cursor != x11rb::NONE {
1873 result = Ok(loaded_cursor);
1874 break 'outer;
1875 }
1876 }
1877 Err(err) => {
1878 errors.push_str(&err.to_string());
1879 errors.push('\n');
1880 }
1881 }
1882 }
1883 if errors.is_empty() {
1884 result = Err(anyhow!(
1885 "errors while loading cursor icons {:?}:\n{}",
1886 cursor_icon_names,
1887 errors
1888 ));
1889 } else {
1890 result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
1891 }
1892 }
1893 };
1894
1895 let cursor = match result {
1896 Ok(cursor) => Some(cursor),
1897 Err(err) => {
1898 match self
1899 .cursor_handle
1900 .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
1901 {
1902 Ok(default) => {
1903 log_cursor_icon_warning(err.context(format!(
1904 "X11: error loading cursor icon, falling back on default icon '{}'",
1905 DEFAULT_CURSOR_ICON_NAME
1906 )));
1907 Some(default)
1908 }
1909 Err(default_err) => {
1910 log_cursor_icon_warning(err.context(default_err).context(format!(
1911 "X11: error loading default cursor fallback '{}'",
1912 DEFAULT_CURSOR_ICON_NAME
1913 )));
1914 None
1915 }
1916 }
1917 }
1918 };
1919
1920 self.cursor_cache.insert(style, cursor);
1921 cursor
1922 }
1923}
1924
1925// Adapted from:
1926// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1927pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1928 if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1929 return Duration::from_millis(16);
1930 }
1931
1932 let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1933 let micros = 1_000_000_000 / millihertz;
1934 log::info!("Refreshing every {}ms", micros / 1_000);
1935 Duration::from_micros(micros)
1936}
1937
1938fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1939 value.integral as f32 + value.frac as f32 / u32::MAX as f32
1940}
1941
1942fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1943 // Method 1: Check for _NET_WM_CM_S{root}
1944 let atom_name = format!("_NET_WM_CM_S{}", root);
1945 let atom1 = get_reply(
1946 || format!("Failed to intern {atom_name}"),
1947 xcb_connection.intern_atom(false, atom_name.as_bytes()),
1948 );
1949 let method1 = match atom1.log_with_level(Level::Debug) {
1950 Some(reply) if reply.atom != x11rb::NONE => {
1951 let atom = reply.atom;
1952 get_reply(
1953 || format!("Failed to get {atom_name} owner"),
1954 xcb_connection.get_selection_owner(atom),
1955 )
1956 .map(|reply| reply.owner != 0)
1957 .log_with_level(Level::Debug)
1958 .unwrap_or(false)
1959 }
1960 _ => false,
1961 };
1962
1963 // Method 2: Check for _NET_WM_CM_OWNER
1964 let atom_name = "_NET_WM_CM_OWNER";
1965 let atom2 = get_reply(
1966 || format!("Failed to intern {atom_name}"),
1967 xcb_connection.intern_atom(false, atom_name.as_bytes()),
1968 );
1969 let method2 = match atom2.log_with_level(Level::Debug) {
1970 Some(reply) if reply.atom != x11rb::NONE => {
1971 let atom = reply.atom;
1972 get_reply(
1973 || format!("Failed to get {atom_name}"),
1974 xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1975 )
1976 .map(|reply| reply.value_len > 0)
1977 .unwrap_or(false)
1978 }
1979 _ => return false,
1980 };
1981
1982 // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1983 let atom_name = "_NET_SUPPORTING_WM_CHECK";
1984 let atom3 = get_reply(
1985 || format!("Failed to intern {atom_name}"),
1986 xcb_connection.intern_atom(false, atom_name.as_bytes()),
1987 );
1988 let method3 = match atom3.log_with_level(Level::Debug) {
1989 Some(reply) if reply.atom != x11rb::NONE => {
1990 let atom = reply.atom;
1991 get_reply(
1992 || format!("Failed to get {atom_name}"),
1993 xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1994 )
1995 .map(|reply| reply.value_len > 0)
1996 .unwrap_or(false)
1997 }
1998 _ => return false,
1999 };
2000
2001 log::debug!(
2002 "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
2003 method1,
2004 method2,
2005 method3
2006 );
2007
2008 method1 || method2 || method3
2009}
2010
2011fn check_gtk_frame_extents_supported(
2012 xcb_connection: &XCBConnection,
2013 atoms: &XcbAtoms,
2014 root: xproto::Window,
2015) -> bool {
2016 let Some(supported_atoms) = get_reply(
2017 || "Failed to get _NET_SUPPORTED",
2018 xcb_connection.get_property(
2019 false,
2020 root,
2021 atoms._NET_SUPPORTED,
2022 xproto::AtomEnum::ATOM,
2023 0,
2024 1024,
2025 ),
2026 )
2027 .log_with_level(Level::Debug) else {
2028 return false;
2029 };
2030
2031 let supported_atom_ids: Vec<u32> = supported_atoms
2032 .value
2033 .chunks_exact(4)
2034 .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
2035 .collect();
2036
2037 supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
2038}
2039
2040fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2041 return atom == atoms.TEXT
2042 || atom == atoms.STRING
2043 || atom == atoms.UTF8_STRING
2044 || atom == atoms.TEXT_PLAIN
2045 || atom == atoms.TEXT_PLAIN_UTF8
2046 || atom == atoms.TextUriList;
2047}
2048
2049fn xdnd_get_supported_atom(
2050 xcb_connection: &XCBConnection,
2051 supported_atoms: &XcbAtoms,
2052 target: xproto::Window,
2053) -> u32 {
2054 if let Some(reply) = get_reply(
2055 || "Failed to get XDnD supported atoms",
2056 xcb_connection.get_property(
2057 false,
2058 target,
2059 supported_atoms.XdndTypeList,
2060 AtomEnum::ANY,
2061 0,
2062 1024,
2063 ),
2064 )
2065 .log_with_level(Level::Warn)
2066 {
2067 if let Some(atoms) = reply.value32() {
2068 for atom in atoms {
2069 if xdnd_is_atom_supported(atom, &supported_atoms) {
2070 return atom;
2071 }
2072 }
2073 }
2074 }
2075 return 0;
2076}
2077
2078fn xdnd_send_finished(
2079 xcb_connection: &XCBConnection,
2080 atoms: &XcbAtoms,
2081 source: xproto::Window,
2082 target: xproto::Window,
2083) {
2084 let message = ClientMessageEvent {
2085 format: 32,
2086 window: target,
2087 type_: atoms.XdndFinished,
2088 data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2089 sequence: 0,
2090 response_type: xproto::CLIENT_MESSAGE_EVENT,
2091 };
2092 check_reply(
2093 || "Failed to send XDnD finished event",
2094 xcb_connection.send_event(false, target, EventMask::default(), message),
2095 )
2096 .log_err();
2097 xcb_connection.flush().log_err();
2098}
2099
2100fn xdnd_send_status(
2101 xcb_connection: &XCBConnection,
2102 atoms: &XcbAtoms,
2103 source: xproto::Window,
2104 target: xproto::Window,
2105 action: u32,
2106) {
2107 let message = ClientMessageEvent {
2108 format: 32,
2109 window: target,
2110 type_: atoms.XdndStatus,
2111 data: ClientMessageData::from([source, 1, 0, 0, action]),
2112 sequence: 0,
2113 response_type: xproto::CLIENT_MESSAGE_EVENT,
2114 };
2115 check_reply(
2116 || "Failed to send XDnD status event",
2117 xcb_connection.send_event(false, target, EventMask::default(), message),
2118 )
2119 .log_err();
2120 xcb_connection.flush().log_err();
2121}
2122
2123/// Recomputes `pointer_device_states` by querying all pointer devices.
2124/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2125fn current_pointer_device_states(
2126 xcb_connection: &XCBConnection,
2127 scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2128) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2129 let devices_query_result = get_reply(
2130 || "Failed to query XInput devices",
2131 xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2132 )
2133 .log_err()?;
2134
2135 let mut pointer_device_states = BTreeMap::new();
2136 pointer_device_states.extend(
2137 devices_query_result
2138 .infos
2139 .iter()
2140 .filter(|info| is_pointer_device(info.type_))
2141 .filter_map(|info| {
2142 let scroll_data = info
2143 .classes
2144 .iter()
2145 .filter_map(|class| class.data.as_scroll())
2146 .map(|class| *class)
2147 .rev()
2148 .collect::<Vec<_>>();
2149 let old_state = scroll_values_to_preserve.get(&info.deviceid);
2150 let old_horizontal = old_state.map(|state| &state.horizontal);
2151 let old_vertical = old_state.map(|state| &state.vertical);
2152 let horizontal = scroll_data
2153 .iter()
2154 .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2155 .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2156 let vertical = scroll_data
2157 .iter()
2158 .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2159 .map(|data| scroll_data_to_axis_state(data, old_vertical));
2160 if horizontal.is_none() && vertical.is_none() {
2161 None
2162 } else {
2163 Some((
2164 info.deviceid,
2165 PointerDeviceState {
2166 horizontal: horizontal.unwrap_or_else(Default::default),
2167 vertical: vertical.unwrap_or_else(Default::default),
2168 },
2169 ))
2170 }
2171 }),
2172 );
2173 if pointer_device_states.is_empty() {
2174 log::error!("Found no xinput mouse pointers.");
2175 }
2176 return Some(pointer_device_states);
2177}
2178
2179/// Returns true if the device is a pointer device. Does not include pointer device groups.
2180fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2181 type_ == xinput::DeviceType::SLAVE_POINTER
2182}
2183
2184fn scroll_data_to_axis_state(
2185 data: &xinput::DeviceClassDataScroll,
2186 old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2187) -> ScrollAxisState {
2188 ScrollAxisState {
2189 valuator_number: Some(data.number),
2190 multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2191 scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2192 }
2193}
2194
2195fn reset_all_pointer_device_scroll_positions(
2196 pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2197) {
2198 pointer_device_states
2199 .iter_mut()
2200 .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2201}
2202
2203fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2204 pointer.horizontal.scroll_value = None;
2205 pointer.vertical.scroll_value = None;
2206}
2207
2208/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2209fn get_scroll_delta_and_update_state(
2210 pointer: &mut PointerDeviceState,
2211 event: &xinput::MotionEvent,
2212) -> Option<Point<f32>> {
2213 let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2214 let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2215 if delta_x.is_some() || delta_y.is_some() {
2216 Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2217 } else {
2218 None
2219 }
2220}
2221
2222fn get_axis_scroll_delta_and_update_state(
2223 event: &xinput::MotionEvent,
2224 axis: &mut ScrollAxisState,
2225) -> Option<f32> {
2226 let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2227 if let Some(axis_value) = event.axisvalues.get(axis_index) {
2228 let new_scroll = fp3232_to_f32(*axis_value);
2229 let delta_scroll = axis
2230 .scroll_value
2231 .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2232 axis.scroll_value = Some(new_scroll);
2233 delta_scroll
2234 } else {
2235 log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2236 None
2237 }
2238}
2239
2240fn make_scroll_wheel_event(
2241 position: Point<Pixels>,
2242 scroll_delta: Point<f32>,
2243 modifiers: Modifiers,
2244) -> crate::ScrollWheelEvent {
2245 // When shift is held down, vertical scrolling turns into horizontal scrolling.
2246 let delta = if modifiers.shift {
2247 Point {
2248 x: scroll_delta.y,
2249 y: 0.0,
2250 }
2251 } else {
2252 scroll_delta
2253 };
2254 crate::ScrollWheelEvent {
2255 position,
2256 delta: ScrollDelta::Lines(delta),
2257 modifiers,
2258 touch_phase: TouchPhase::default(),
2259 }
2260}
2261
2262fn create_invisible_cursor(
2263 connection: &XCBConnection,
2264) -> anyhow::Result<crate::platform::linux::x11::client::xproto::Cursor> {
2265 let empty_pixmap = connection.generate_id()?;
2266 let root = connection.setup().roots[0].root;
2267 connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2268
2269 let cursor = connection.generate_id()?;
2270 connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2271
2272 connection.free_pixmap(empty_pixmap)?;
2273
2274 xcb_flush(connection);
2275 Ok(cursor)
2276}