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