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