1use std::{rc::Rc, sync::Arc};
2
3use parking_lot::Mutex;
4use xcb::{x, Xid as _};
5use xkbcommon::xkb;
6
7use collections::HashMap;
8
9use crate::platform::linux::client::Client;
10use crate::platform::{
11 LinuxPlatformInner, PlatformWindow, X11Display, X11Window, X11WindowState, XcbAtoms,
12};
13use crate::{
14 AnyWindowHandle, Bounds, DisplayId, PlatformDisplay, PlatformInput, Point, ScrollDelta, Size,
15 TouchPhase, WindowOptions,
16};
17
18pub(crate) struct X11ClientState {
19 pub(crate) windows: HashMap<x::Window, Rc<X11WindowState>>,
20 xkb: xkbcommon::xkb::State,
21}
22
23pub(crate) struct X11Client {
24 platform_inner: Rc<LinuxPlatformInner>,
25 xcb_connection: Arc<xcb::Connection>,
26 x_root_index: i32,
27 atoms: XcbAtoms,
28 state: Mutex<X11ClientState>,
29}
30
31impl X11Client {
32 pub(crate) fn new(
33 inner: Rc<LinuxPlatformInner>,
34 xcb_connection: Arc<xcb::Connection>,
35 x_root_index: i32,
36 atoms: XcbAtoms,
37 ) -> Self {
38 let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
39 let xkb_device_id = xkb::x11::get_core_keyboard_device_id(&xcb_connection);
40 let xkb_keymap = xkb::x11::keymap_new_from_device(
41 &xkb_context,
42 &xcb_connection,
43 xkb_device_id,
44 xkb::KEYMAP_COMPILE_NO_FLAGS,
45 );
46 let xkb_state =
47 xkb::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id);
48
49 Self {
50 platform_inner: inner,
51 xcb_connection,
52 x_root_index,
53 atoms,
54 state: Mutex::new(X11ClientState {
55 windows: HashMap::default(),
56 xkb: xkb_state,
57 }),
58 }
59 }
60
61 fn get_window(&self, win: x::Window) -> Rc<X11WindowState> {
62 let state = self.state.lock();
63 Rc::clone(&state.windows[&win])
64 }
65}
66
67impl Client for X11Client {
68 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
69 on_finish_launching();
70 //Note: here and below, don't keep the lock() open when calling
71 // into window functions as they may invoke callbacks that need
72 // to immediately access the platform (self).
73 while !self.platform_inner.state.lock().quit_requested {
74 let event = self.xcb_connection.wait_for_event().unwrap();
75 match event {
76 xcb::Event::X(x::Event::ClientMessage(ev)) => {
77 if let x::ClientMessageData::Data32([atom, ..]) = ev.data() {
78 if atom == self.atoms.wm_del_window.resource_id() {
79 // window "x" button clicked by user, we gracefully exit
80 let window = self.state.lock().windows.remove(&ev.window()).unwrap();
81 window.destroy();
82 let state = self.state.lock();
83 self.platform_inner.state.lock().quit_requested |=
84 state.windows.is_empty();
85 }
86 }
87 }
88 xcb::Event::X(x::Event::Expose(ev)) => {
89 self.get_window(ev.window()).refresh();
90 }
91 xcb::Event::X(x::Event::ConfigureNotify(ev)) => {
92 let bounds = Bounds {
93 origin: Point {
94 x: ev.x().into(),
95 y: ev.y().into(),
96 },
97 size: Size {
98 width: ev.width().into(),
99 height: ev.height().into(),
100 },
101 };
102 self.get_window(ev.window()).configure(bounds)
103 }
104 xcb::Event::Present(xcb::present::Event::CompleteNotify(ev)) => {
105 let window = self.get_window(ev.window());
106 window.refresh();
107 window.request_refresh();
108 }
109 xcb::Event::Present(xcb::present::Event::IdleNotify(_ev)) => {}
110 xcb::Event::X(x::Event::FocusIn(ev)) => {
111 let window = self.get_window(ev.event());
112 window.set_focused(true);
113 }
114 xcb::Event::X(x::Event::FocusOut(ev)) => {
115 let window = self.get_window(ev.event());
116 window.set_focused(false);
117 }
118 xcb::Event::X(x::Event::KeyPress(ev)) => {
119 let window = self.get_window(ev.event());
120 let modifiers = super::modifiers_from_state(ev.state());
121 let keystroke = {
122 let code = ev.detail().into();
123 let mut state = self.state.lock();
124 let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
125 state.xkb.update_key(code, xkb::KeyDirection::Down);
126 keystroke
127 };
128
129 window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
130 keystroke,
131 is_held: false,
132 }));
133 }
134 xcb::Event::X(x::Event::KeyRelease(ev)) => {
135 let window = self.get_window(ev.event());
136 let modifiers = super::modifiers_from_state(ev.state());
137 let keystroke = {
138 let code = ev.detail().into();
139 let mut state = self.state.lock();
140 let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
141 state.xkb.update_key(code, xkb::KeyDirection::Up);
142 keystroke
143 };
144
145 window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
146 }
147 xcb::Event::X(x::Event::ButtonPress(ev)) => {
148 let window = self.get_window(ev.event());
149 let modifiers = super::modifiers_from_state(ev.state());
150 let position =
151 Point::new((ev.event_x() as f32).into(), (ev.event_y() as f32).into());
152 if let Some(button) = super::button_of_key(ev.detail()) {
153 window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
154 button,
155 position,
156 modifiers,
157 click_count: 1,
158 }));
159 } else if ev.detail() >= 4 && ev.detail() <= 5 {
160 // https://stackoverflow.com/questions/15510472/scrollwheel-event-in-x11
161 let delta_x = if ev.detail() == 4 { 1.0 } else { -1.0 };
162 window.handle_input(PlatformInput::ScrollWheel(crate::ScrollWheelEvent {
163 position,
164 delta: ScrollDelta::Lines(Point::new(0.0, delta_x)),
165 modifiers,
166 touch_phase: TouchPhase::default(),
167 }));
168 } else {
169 log::warn!("Unknown button press: {ev:?}");
170 }
171 }
172 xcb::Event::X(x::Event::ButtonRelease(ev)) => {
173 let window = self.get_window(ev.event());
174 let modifiers = super::modifiers_from_state(ev.state());
175 let position =
176 Point::new((ev.event_x() as f32).into(), (ev.event_y() as f32).into());
177 if let Some(button) = super::button_of_key(ev.detail()) {
178 window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
179 button,
180 position,
181 modifiers,
182 click_count: 1,
183 }));
184 }
185 }
186 xcb::Event::X(x::Event::MotionNotify(ev)) => {
187 let window = self.get_window(ev.event());
188 let pressed_button = super::button_from_state(ev.state());
189 let position =
190 Point::new((ev.event_x() as f32).into(), (ev.event_y() as f32).into());
191 let modifiers = super::modifiers_from_state(ev.state());
192 window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
193 pressed_button,
194 position,
195 modifiers,
196 }));
197 }
198 xcb::Event::X(x::Event::LeaveNotify(ev)) => {
199 let window = self.get_window(ev.event());
200 let pressed_button = super::button_from_state(ev.state());
201 let position =
202 Point::new((ev.event_x() as f32).into(), (ev.event_y() as f32).into());
203 let modifiers = super::modifiers_from_state(ev.state());
204 window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
205 pressed_button,
206 position,
207 modifiers,
208 }));
209 }
210 _ => {}
211 }
212
213 if let Ok(runnable) = self.platform_inner.main_receiver.try_recv() {
214 runnable.run();
215 }
216 }
217
218 if let Some(ref mut fun) = self.platform_inner.callbacks.lock().quit {
219 fun();
220 }
221 }
222 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
223 let setup = self.xcb_connection.get_setup();
224 setup
225 .roots()
226 .enumerate()
227 .map(|(root_id, _)| {
228 Rc::new(X11Display::new(&self.xcb_connection, root_id as i32))
229 as Rc<dyn PlatformDisplay>
230 })
231 .collect()
232 }
233 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
234 Some(Rc::new(X11Display::new(&self.xcb_connection, id.0 as i32)))
235 }
236
237 fn open_window(
238 &self,
239 _handle: AnyWindowHandle,
240 options: WindowOptions,
241 ) -> Box<dyn PlatformWindow> {
242 let x_window = self.xcb_connection.generate_id();
243
244 let window_ptr = Rc::new(X11WindowState::new(
245 options,
246 &self.xcb_connection,
247 self.x_root_index,
248 x_window,
249 &self.atoms,
250 ));
251 window_ptr.request_refresh();
252
253 self.state
254 .lock()
255 .windows
256 .insert(x_window, Rc::clone(&window_ptr));
257 Box::new(X11Window(window_ptr))
258 }
259}