client.rs

  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 = {
 75                profiling::scope!("Wait for event");
 76                self.xcb_connection.wait_for_event().unwrap()
 77            };
 78            match event {
 79                xcb::Event::X(x::Event::ClientMessage(ev)) => {
 80                    if let x::ClientMessageData::Data32([atom, ..]) = ev.data() {
 81                        if atom == self.atoms.wm_del_window.resource_id() {
 82                            // window "x" button clicked by user, we gracefully exit
 83                            let window = self.state.lock().windows.remove(&ev.window()).unwrap();
 84                            window.destroy();
 85                            let state = self.state.lock();
 86                            self.platform_inner.state.lock().quit_requested |=
 87                                state.windows.is_empty();
 88                        }
 89                    }
 90                }
 91                xcb::Event::X(x::Event::Expose(ev)) => {
 92                    self.get_window(ev.window()).refresh();
 93                }
 94                xcb::Event::X(x::Event::ConfigureNotify(ev)) => {
 95                    let bounds = Bounds {
 96                        origin: Point {
 97                            x: ev.x().into(),
 98                            y: ev.y().into(),
 99                        },
100                        size: Size {
101                            width: ev.width().into(),
102                            height: ev.height().into(),
103                        },
104                    };
105                    self.get_window(ev.window()).configure(bounds)
106                }
107                xcb::Event::Present(xcb::present::Event::CompleteNotify(ev)) => {
108                    let window = self.get_window(ev.window());
109                    window.refresh();
110                    window.request_refresh();
111                }
112                xcb::Event::Present(xcb::present::Event::IdleNotify(_ev)) => {}
113                xcb::Event::X(x::Event::FocusIn(ev)) => {
114                    let window = self.get_window(ev.event());
115                    window.set_focused(true);
116                }
117                xcb::Event::X(x::Event::FocusOut(ev)) => {
118                    let window = self.get_window(ev.event());
119                    window.set_focused(false);
120                }
121                xcb::Event::X(x::Event::KeyPress(ev)) => {
122                    let window = self.get_window(ev.event());
123                    let modifiers = super::modifiers_from_state(ev.state());
124                    let keystroke = {
125                        let code = ev.detail().into();
126                        let mut state = self.state.lock();
127                        let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
128                        state.xkb.update_key(code, xkb::KeyDirection::Down);
129                        keystroke
130                    };
131
132                    window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
133                        keystroke,
134                        is_held: false,
135                    }));
136                }
137                xcb::Event::X(x::Event::KeyRelease(ev)) => {
138                    let window = self.get_window(ev.event());
139                    let modifiers = super::modifiers_from_state(ev.state());
140                    let keystroke = {
141                        let code = ev.detail().into();
142                        let mut state = self.state.lock();
143                        let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
144                        state.xkb.update_key(code, xkb::KeyDirection::Up);
145                        keystroke
146                    };
147
148                    window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
149                }
150                xcb::Event::X(x::Event::ButtonPress(ev)) => {
151                    let window = self.get_window(ev.event());
152                    let modifiers = super::modifiers_from_state(ev.state());
153                    let position =
154                        Point::new((ev.event_x() as f32).into(), (ev.event_y() as f32).into());
155                    if let Some(button) = super::button_of_key(ev.detail()) {
156                        window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
157                            button,
158                            position,
159                            modifiers,
160                            click_count: 1,
161                        }));
162                    } else if ev.detail() >= 4 && ev.detail() <= 5 {
163                        // https://stackoverflow.com/questions/15510472/scrollwheel-event-in-x11
164                        let delta_x = if ev.detail() == 4 { 1.0 } else { -1.0 };
165                        window.handle_input(PlatformInput::ScrollWheel(crate::ScrollWheelEvent {
166                            position,
167                            delta: ScrollDelta::Lines(Point::new(0.0, delta_x)),
168                            modifiers,
169                            touch_phase: TouchPhase::default(),
170                        }));
171                    } else {
172                        log::warn!("Unknown button press: {ev:?}");
173                    }
174                }
175                xcb::Event::X(x::Event::ButtonRelease(ev)) => {
176                    let window = self.get_window(ev.event());
177                    let modifiers = super::modifiers_from_state(ev.state());
178                    let position =
179                        Point::new((ev.event_x() as f32).into(), (ev.event_y() as f32).into());
180                    if let Some(button) = super::button_of_key(ev.detail()) {
181                        window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
182                            button,
183                            position,
184                            modifiers,
185                            click_count: 1,
186                        }));
187                    }
188                }
189                xcb::Event::X(x::Event::MotionNotify(ev)) => {
190                    let window = self.get_window(ev.event());
191                    let pressed_button = super::button_from_state(ev.state());
192                    let position =
193                        Point::new((ev.event_x() as f32).into(), (ev.event_y() as f32).into());
194                    let modifiers = super::modifiers_from_state(ev.state());
195                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
196                        pressed_button,
197                        position,
198                        modifiers,
199                    }));
200                }
201                xcb::Event::X(x::Event::LeaveNotify(ev)) => {
202                    let window = self.get_window(ev.event());
203                    let pressed_button = super::button_from_state(ev.state());
204                    let position =
205                        Point::new((ev.event_x() as f32).into(), (ev.event_y() as f32).into());
206                    let modifiers = super::modifiers_from_state(ev.state());
207                    window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
208                        pressed_button,
209                        position,
210                        modifiers,
211                    }));
212                }
213                _ => {}
214            }
215
216            profiling::scope!("Runnables");
217            if let Ok(runnable) = self.platform_inner.main_receiver.try_recv() {
218                runnable.run();
219            }
220        }
221
222        if let Some(ref mut fun) = self.platform_inner.callbacks.lock().quit {
223            fun();
224        }
225    }
226
227    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
228        let setup = self.xcb_connection.get_setup();
229        setup
230            .roots()
231            .enumerate()
232            .map(|(root_id, _)| {
233                Rc::new(X11Display::new(&self.xcb_connection, root_id as i32))
234                    as Rc<dyn PlatformDisplay>
235            })
236            .collect()
237    }
238
239    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
240        Some(Rc::new(X11Display::new(&self.xcb_connection, id.0 as i32)))
241    }
242
243    fn open_window(
244        &self,
245        _handle: AnyWindowHandle,
246        options: WindowOptions,
247    ) -> Box<dyn PlatformWindow> {
248        let x_window = self.xcb_connection.generate_id();
249
250        let window_ptr = Rc::new(X11WindowState::new(
251            options,
252            &self.xcb_connection,
253            self.x_root_index,
254            x_window,
255            &self.atoms,
256        ));
257        window_ptr.request_refresh();
258
259        self.state
260            .lock()
261            .windows
262            .insert(x_window, Rc::clone(&window_ptr));
263        Box::new(X11Window(window_ptr))
264    }
265}