1use std::cell::RefCell;
2use std::ops::Deref;
3use std::rc::{Rc, Weak};
4use std::time::{Duration, Instant};
5
6use calloop::{EventLoop, LoopHandle};
7use collections::HashMap;
8use copypasta::x11_clipboard::{Clipboard, Primary, X11ClipboardContext};
9use copypasta::ClipboardProvider;
10
11use util::ResultExt;
12use x11rb::connection::{Connection, RequestConnection};
13use x11rb::errors::ConnectionError;
14use x11rb::protocol::randr::ConnectionExt as _;
15use x11rb::protocol::xinput::{ConnectionExt, ScrollClass};
16use x11rb::protocol::xkb::ConnectionExt as _;
17use x11rb::protocol::xproto::ConnectionExt as _;
18use x11rb::protocol::{randr, xinput, xkb, xproto, Event};
19use x11rb::resource_manager::Database;
20use x11rb::xcb_ffi::XCBConnection;
21use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
22use xkbcommon::xkb as xkbc;
23
24use crate::platform::linux::LinuxClient;
25use crate::platform::{LinuxCommon, PlatformWindow};
26use crate::{
27 modifiers_from_xinput_info, point, px, AnyWindowHandle, Bounds, CursorStyle, DisplayId,
28 Modifiers, ModifiersChangedEvent, Pixels, PlatformDisplay, PlatformInput, Point, ScrollDelta,
29 Size, TouchPhase, WindowParams, X11Window,
30};
31
32use super::{
33 super::{open_uri_internal, SCROLL_LINES},
34 X11Display, X11WindowStatePtr, XcbAtoms,
35};
36use super::{button_of_key, modifiers_from_state};
37use crate::platform::linux::is_within_click_distance;
38use crate::platform::linux::platform::DOUBLE_CLICK_INTERVAL;
39use calloop::{
40 generic::{FdWrapper, Generic},
41 RegistrationToken,
42};
43
44pub(crate) struct WindowRef {
45 window: X11WindowStatePtr,
46 refresh_event_token: RegistrationToken,
47}
48
49impl Deref for WindowRef {
50 type Target = X11WindowStatePtr;
51
52 fn deref(&self) -> &Self::Target {
53 &self.window
54 }
55}
56
57pub struct X11ClientState {
58 pub(crate) loop_handle: LoopHandle<'static, X11Client>,
59 pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
60
61 pub(crate) last_click: Instant,
62 pub(crate) last_location: Point<Pixels>,
63 pub(crate) current_count: usize,
64
65 pub(crate) scale_factor: f32,
66
67 pub(crate) xcb_connection: Rc<XCBConnection>,
68 pub(crate) x_root_index: usize,
69 pub(crate) resource_database: Database,
70 pub(crate) atoms: XcbAtoms,
71 pub(crate) windows: HashMap<xproto::Window, WindowRef>,
72 pub(crate) focused_window: Option<xproto::Window>,
73 pub(crate) xkb: xkbc::State,
74
75 pub(crate) scroll_class_data: Vec<xinput::DeviceClassDataScroll>,
76 pub(crate) scroll_x: Option<f32>,
77 pub(crate) scroll_y: Option<f32>,
78
79 pub(crate) common: LinuxCommon,
80 pub(crate) clipboard: X11ClipboardContext<Clipboard>,
81 pub(crate) primary: X11ClipboardContext<Primary>,
82}
83
84#[derive(Clone)]
85pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
86
87impl X11ClientStatePtr {
88 pub fn drop_window(&self, x_window: u32) {
89 let client = X11Client(self.0.upgrade().expect("client already dropped"));
90 let mut state = client.0.borrow_mut();
91
92 if let Some(window_ref) = state.windows.remove(&x_window) {
93 state.loop_handle.remove(window_ref.refresh_event_token);
94 }
95
96 if state.windows.is_empty() {
97 state.common.signal.stop();
98 }
99 }
100}
101
102#[derive(Clone)]
103pub(crate) struct X11Client(Rc<RefCell<X11ClientState>>);
104
105impl X11Client {
106 pub(crate) fn new() -> Self {
107 let event_loop = EventLoop::try_new().unwrap();
108
109 let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
110
111 let handle = event_loop.handle();
112
113 handle.insert_source(main_receiver, |event, _, _: &mut X11Client| {
114 if let calloop::channel::Event::Msg(runnable) = event {
115 runnable.run();
116 }
117 });
118
119 let (xcb_connection, x_root_index) = XCBConnection::connect(None).unwrap();
120 xcb_connection
121 .prefetch_extension_information(xkb::X11_EXTENSION_NAME)
122 .unwrap();
123 xcb_connection
124 .prefetch_extension_information(randr::X11_EXTENSION_NAME)
125 .unwrap();
126 xcb_connection
127 .prefetch_extension_information(xinput::X11_EXTENSION_NAME)
128 .unwrap();
129
130 let xinput_version = xcb_connection
131 .xinput_xi_query_version(2, 0)
132 .unwrap()
133 .reply()
134 .unwrap();
135 assert!(
136 xinput_version.major_version >= 2,
137 "XInput Extension v2 not supported."
138 );
139
140 let master_device_query = xcb_connection
141 .xinput_xi_query_device(1_u16)
142 .unwrap()
143 .reply()
144 .unwrap();
145 let scroll_class_data = master_device_query
146 .infos
147 .iter()
148 .find(|info| info.type_ == xinput::DeviceType::MASTER_POINTER)
149 .unwrap()
150 .classes
151 .iter()
152 .filter_map(|class| class.data.as_scroll())
153 .map(|class| *class)
154 .collect::<Vec<_>>();
155
156 let atoms = XcbAtoms::new(&xcb_connection).unwrap();
157 let xkb = xcb_connection
158 .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION)
159 .unwrap();
160
161 let atoms = atoms.reply().unwrap();
162 let xkb = xkb.reply().unwrap();
163 let events = xkb::EventType::STATE_NOTIFY;
164 xcb_connection
165 .xkb_select_events(
166 xkb::ID::USE_CORE_KBD.into(),
167 0u8.into(),
168 events,
169 0u8.into(),
170 0u8.into(),
171 &xkb::SelectEventsAux::new(),
172 )
173 .unwrap();
174 assert!(xkb.supported);
175
176 let xkb_state = {
177 let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
178 let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
179 let xkb_keymap = xkbc::x11::keymap_new_from_device(
180 &xkb_context,
181 &xcb_connection,
182 xkb_device_id,
183 xkbc::KEYMAP_COMPILE_NO_FLAGS,
184 );
185 xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
186 };
187
188 let screen = xcb_connection.setup().roots.get(x_root_index).unwrap();
189
190 // Values from `Database::GET_RESOURCE_DATABASE`
191 let resource_manager = xcb_connection
192 .get_property(
193 false,
194 screen.root,
195 xproto::AtomEnum::RESOURCE_MANAGER,
196 xproto::AtomEnum::STRING,
197 0,
198 100_000_000,
199 )
200 .unwrap();
201 let resource_manager = resource_manager.reply().unwrap();
202
203 // todo(linux): read hostname
204 let resource_database = Database::new_from_default(&resource_manager, "HOSTNAME".into());
205
206 let scale_factor = resource_database
207 .get_value("Xft.dpi", "Xft.dpi")
208 .ok()
209 .flatten()
210 .map(|dpi: f32| dpi / 96.0)
211 .unwrap_or(1.0);
212
213 let clipboard = X11ClipboardContext::<Clipboard>::new().unwrap();
214 let primary = X11ClipboardContext::<Primary>::new().unwrap();
215
216 let xcb_connection = Rc::new(xcb_connection);
217
218 // Safety: Safe if xcb::Connection always returns a valid fd
219 let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
220
221 handle
222 .insert_source(
223 Generic::new_with_error::<ConnectionError>(
224 fd,
225 calloop::Interest::READ,
226 calloop::Mode::Level,
227 ),
228 {
229 let xcb_connection = xcb_connection.clone();
230 move |_readiness, _, client| {
231 while let Some(event) = xcb_connection.poll_for_event()? {
232 client.handle_event(event);
233 }
234 Ok(calloop::PostAction::Continue)
235 }
236 },
237 )
238 .expect("Failed to initialize x11 event source");
239
240 X11Client(Rc::new(RefCell::new(X11ClientState {
241 event_loop: Some(event_loop),
242 loop_handle: handle,
243 common,
244 last_click: Instant::now(),
245 last_location: Point::new(px(0.0), px(0.0)),
246 current_count: 0,
247 scale_factor,
248
249 xcb_connection,
250 x_root_index,
251 resource_database,
252 atoms,
253 windows: HashMap::default(),
254 focused_window: None,
255 xkb: xkb_state,
256
257 scroll_class_data,
258 scroll_x: None,
259 scroll_y: None,
260
261 clipboard,
262 primary,
263 })))
264 }
265
266 fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
267 let state = self.0.borrow();
268 state
269 .windows
270 .get(&win)
271 .map(|window_reference| window_reference.window.clone())
272 }
273
274 fn handle_event(&self, event: Event) -> Option<()> {
275 match event {
276 Event::ClientMessage(event) => {
277 let window = self.get_window(event.window)?;
278 let [atom, ..] = event.data.as_data32();
279 let mut state = self.0.borrow_mut();
280
281 if atom == state.atoms.WM_DELETE_WINDOW {
282 // window "x" button clicked by user
283 if window.should_close() {
284 let window_ref = state.windows.remove(&event.window)?;
285 state.loop_handle.remove(window_ref.refresh_event_token);
286 // Rest of the close logic is handled in drop_window()
287 }
288 }
289 }
290 Event::ConfigureNotify(event) => {
291 let bounds = Bounds {
292 origin: Point {
293 x: event.x.into(),
294 y: event.y.into(),
295 },
296 size: Size {
297 width: event.width.into(),
298 height: event.height.into(),
299 },
300 };
301 let window = self.get_window(event.window)?;
302 window.configure(bounds);
303 }
304 Event::Expose(event) => {
305 let window = self.get_window(event.window)?;
306 window.refresh();
307 }
308 Event::FocusIn(event) => {
309 let window = self.get_window(event.event)?;
310 window.set_focused(true);
311 self.0.borrow_mut().focused_window = Some(event.event);
312 }
313 Event::FocusOut(event) => {
314 let window = self.get_window(event.event)?;
315 window.set_focused(false);
316 self.0.borrow_mut().focused_window = None;
317 }
318 Event::XkbStateNotify(event) => {
319 let mut state = self.0.borrow_mut();
320 state.xkb.update_mask(
321 event.base_mods.into(),
322 event.latched_mods.into(),
323 event.locked_mods.into(),
324 0,
325 0,
326 event.locked_group.into(),
327 );
328 let modifiers = Modifiers::from_xkb(&state.xkb);
329 let focused_window_id = state.focused_window?;
330 drop(state);
331
332 let focused_window = self.get_window(focused_window_id)?;
333 focused_window.handle_input(PlatformInput::ModifiersChanged(
334 ModifiersChangedEvent { modifiers },
335 ));
336 }
337 Event::KeyPress(event) => {
338 let window = self.get_window(event.event)?;
339 let mut state = self.0.borrow_mut();
340
341 let modifiers = modifiers_from_state(event.state);
342 let keystroke = {
343 let code = event.detail.into();
344 let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
345 state.xkb.update_key(code, xkbc::KeyDirection::Down);
346 let keysym = state.xkb.key_get_one_sym(code);
347 if keysym.is_modifier_key() {
348 return Some(());
349 }
350 keystroke
351 };
352
353 drop(state);
354 window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
355 keystroke,
356 is_held: false,
357 }));
358 }
359 Event::KeyRelease(event) => {
360 let window = self.get_window(event.event)?;
361 let mut state = self.0.borrow_mut();
362
363 let modifiers = modifiers_from_state(event.state);
364 let keystroke = {
365 let code = event.detail.into();
366 let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
367 state.xkb.update_key(code, xkbc::KeyDirection::Up);
368 let keysym = state.xkb.key_get_one_sym(code);
369 if keysym.is_modifier_key() {
370 return Some(());
371 }
372 keystroke
373 };
374 drop(state);
375 window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
376 }
377 Event::ButtonPress(event) => {
378 let window = self.get_window(event.event)?;
379 let mut state = self.0.borrow_mut();
380
381 let modifiers = modifiers_from_state(event.state);
382 let position = point(
383 px(event.event_x as f32 / state.scale_factor),
384 px(event.event_y as f32 / state.scale_factor),
385 );
386 if let Some(button) = button_of_key(event.detail) {
387 let click_elapsed = state.last_click.elapsed();
388
389 if click_elapsed < DOUBLE_CLICK_INTERVAL
390 && is_within_click_distance(state.last_location, position)
391 {
392 state.current_count += 1;
393 } else {
394 state.current_count = 1;
395 }
396
397 state.last_click = Instant::now();
398 state.last_location = position;
399 let current_count = state.current_count;
400
401 drop(state);
402 window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
403 button,
404 position,
405 modifiers,
406 click_count: current_count,
407 first_mouse: false,
408 }));
409 } else {
410 log::warn!("Unknown button press: {event:?}");
411 }
412 }
413 Event::ButtonRelease(event) => {
414 let window = self.get_window(event.event)?;
415 let state = self.0.borrow();
416 let modifiers = modifiers_from_state(event.state);
417 let position = point(
418 px(event.event_x as f32 / state.scale_factor),
419 px(event.event_y as f32 / state.scale_factor),
420 );
421 if let Some(button) = button_of_key(event.detail) {
422 let click_count = state.current_count;
423 drop(state);
424 window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
425 button,
426 position,
427 modifiers,
428 click_count,
429 }));
430 }
431 }
432 Event::XinputMotion(event) => {
433 let window = self.get_window(event.event)?;
434 let state = self.0.borrow();
435 let position = point(
436 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
437 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
438 );
439 drop(state);
440 let modifiers = modifiers_from_xinput_info(event.mods);
441
442 let axisvalues = event
443 .axisvalues
444 .iter()
445 .map(|axisvalue| fp3232_to_f32(*axisvalue))
446 .collect::<Vec<_>>();
447
448 if event.valuator_mask[0] & 3 != 0 {
449 window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
450 position,
451 pressed_button: None,
452 modifiers,
453 }));
454 }
455
456 let mut valuator_idx = 0;
457 let scroll_class_data = self.0.borrow().scroll_class_data.clone();
458 for shift in 0..32 {
459 if (event.valuator_mask[0] >> shift) & 1 == 0 {
460 continue;
461 }
462
463 for scroll_class in &scroll_class_data {
464 if scroll_class.scroll_type == xinput::ScrollType::HORIZONTAL
465 && scroll_class.number == shift
466 {
467 let new_scroll = axisvalues[valuator_idx]
468 / fp3232_to_f32(scroll_class.increment)
469 * SCROLL_LINES as f32;
470 let old_scroll = self.0.borrow().scroll_x;
471 self.0.borrow_mut().scroll_x = Some(new_scroll);
472
473 if let Some(old_scroll) = old_scroll {
474 let delta_scroll = old_scroll - new_scroll;
475 window.handle_input(PlatformInput::ScrollWheel(
476 crate::ScrollWheelEvent {
477 position,
478 delta: ScrollDelta::Lines(Point::new(delta_scroll, 0.0)),
479 modifiers,
480 touch_phase: TouchPhase::default(),
481 },
482 ));
483 }
484 } else if scroll_class.scroll_type == xinput::ScrollType::VERTICAL
485 && scroll_class.number == shift
486 {
487 // the `increment` is the valuator delta equivalent to one positive unit of scrolling. Here that means SCROLL_LINES lines.
488 let new_scroll = axisvalues[valuator_idx]
489 / fp3232_to_f32(scroll_class.increment)
490 * SCROLL_LINES as f32;
491 let old_scroll = self.0.borrow().scroll_y;
492 self.0.borrow_mut().scroll_y = Some(new_scroll);
493
494 if let Some(old_scroll) = old_scroll {
495 let delta_scroll = old_scroll - new_scroll;
496 window.handle_input(PlatformInput::ScrollWheel(
497 crate::ScrollWheelEvent {
498 position,
499 delta: ScrollDelta::Lines(Point::new(0.0, delta_scroll)),
500 modifiers,
501 touch_phase: TouchPhase::default(),
502 },
503 ));
504 }
505 }
506 }
507
508 valuator_idx += 1;
509 }
510 }
511 Event::MotionNotify(event) => {
512 let window = self.get_window(event.event)?;
513 let state = self.0.borrow();
514 let pressed_button = super::button_from_state(event.state);
515 let position = point(
516 px(event.event_x as f32 / state.scale_factor),
517 px(event.event_y as f32 / state.scale_factor),
518 );
519 let modifiers = modifiers_from_state(event.state);
520 drop(state);
521 window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
522 pressed_button,
523 position,
524 modifiers,
525 }));
526 }
527 Event::LeaveNotify(event) => {
528 let window = self.get_window(event.event)?;
529 let state = self.0.borrow();
530 let pressed_button = super::button_from_state(event.state);
531 let position = point(
532 px(event.event_x as f32 / state.scale_factor),
533 px(event.event_y as f32 / state.scale_factor),
534 );
535 let modifiers = modifiers_from_state(event.state);
536 drop(state);
537 window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
538 pressed_button,
539 position,
540 modifiers,
541 }));
542 }
543 _ => {}
544 };
545
546 Some(())
547 }
548}
549
550impl LinuxClient for X11Client {
551 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
552 f(&mut self.0.borrow_mut().common)
553 }
554
555 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
556 let state = self.0.borrow();
557 let setup = state.xcb_connection.setup();
558 setup
559 .roots
560 .iter()
561 .enumerate()
562 .filter_map(|(root_id, _)| {
563 Some(Rc::new(X11Display::new(&state.xcb_connection, root_id)?)
564 as Rc<dyn PlatformDisplay>)
565 })
566 .collect()
567 }
568
569 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
570 let state = self.0.borrow();
571
572 Some(Rc::new(
573 X11Display::new(&state.xcb_connection, state.x_root_index)
574 .expect("There should always be a root index"),
575 ))
576 }
577
578 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
579 let state = self.0.borrow();
580
581 Some(Rc::new(X11Display::new(
582 &state.xcb_connection,
583 id.0 as usize,
584 )?))
585 }
586
587 fn open_window(
588 &self,
589 _handle: AnyWindowHandle,
590 params: WindowParams,
591 ) -> Box<dyn PlatformWindow> {
592 let mut state = self.0.borrow_mut();
593 let x_window = state.xcb_connection.generate_id().unwrap();
594
595 let window = X11Window::new(
596 X11ClientStatePtr(Rc::downgrade(&self.0)),
597 state.common.foreground_executor.clone(),
598 params,
599 &state.xcb_connection,
600 state.x_root_index,
601 x_window,
602 &state.atoms,
603 state.scale_factor,
604 );
605
606 let screen_resources = state
607 .xcb_connection
608 .randr_get_screen_resources(x_window)
609 .unwrap()
610 .reply()
611 .expect("Could not find available screens");
612
613 let mode = screen_resources
614 .crtcs
615 .iter()
616 .find_map(|crtc| {
617 let crtc_info = state
618 .xcb_connection
619 .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
620 .ok()?
621 .reply()
622 .ok()?;
623
624 screen_resources
625 .modes
626 .iter()
627 .find(|m| m.id == crtc_info.mode)
628 })
629 .expect("Unable to find screen refresh rate");
630
631 let refresh_event_token = state
632 .loop_handle
633 .insert_source(calloop::timer::Timer::immediate(), {
634 let refresh_duration = mode_refresh_rate(mode);
635 move |mut instant, (), client| {
636 let state = client.0.borrow_mut();
637 state
638 .xcb_connection
639 .send_event(
640 false,
641 x_window,
642 xproto::EventMask::EXPOSURE,
643 xproto::ExposeEvent {
644 response_type: xproto::EXPOSE_EVENT,
645 sequence: 0,
646 window: x_window,
647 x: 0,
648 y: 0,
649 width: 0,
650 height: 0,
651 count: 1,
652 },
653 )
654 .unwrap();
655 let _ = state.xcb_connection.flush().unwrap();
656 // Take into account that some frames have been skipped
657 let now = time::Instant::now();
658 while instant < now {
659 instant += refresh_duration;
660 }
661 calloop::timer::TimeoutAction::ToInstant(instant)
662 }
663 })
664 .expect("Failed to initialize refresh timer");
665
666 let window_ref = WindowRef {
667 window: window.0.clone(),
668 refresh_event_token,
669 };
670
671 state.windows.insert(x_window, window_ref);
672 Box::new(window)
673 }
674
675 //todo(linux)
676 fn set_cursor_style(&self, _style: CursorStyle) {}
677
678 fn open_uri(&self, uri: &str) {
679 open_uri_internal(uri, None);
680 }
681
682 fn write_to_primary(&self, item: crate::ClipboardItem) {
683 self.0.borrow_mut().primary.set_contents(item.text);
684 }
685
686 fn write_to_clipboard(&self, item: crate::ClipboardItem) {
687 self.0.borrow_mut().clipboard.set_contents(item.text);
688 }
689
690 fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
691 self.0
692 .borrow_mut()
693 .primary
694 .get_contents()
695 .ok()
696 .map(|text| crate::ClipboardItem {
697 text,
698 metadata: None,
699 })
700 }
701
702 fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
703 self.0
704 .borrow_mut()
705 .clipboard
706 .get_contents()
707 .ok()
708 .map(|text| crate::ClipboardItem {
709 text,
710 metadata: None,
711 })
712 }
713
714 fn run(&self) {
715 let mut event_loop = self
716 .0
717 .borrow_mut()
718 .event_loop
719 .take()
720 .expect("App is already running");
721
722 event_loop.run(None, &mut self.clone(), |_| {}).log_err();
723 }
724}
725
726// Adatpted from:
727// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
728pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
729 let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
730 let micros = 1_000_000_000 / millihertz;
731 log::info!("Refreshing at {} micros", micros);
732 Duration::from_micros(micros)
733}
734
735fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
736 value.integral as f32 + value.frac as f32 / u32::MAX as f32
737}