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