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