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