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