client.rs

   1use std::cell::RefCell;
   2use std::ffi::OsString;
   3use std::ops::Deref;
   4use std::rc::{Rc, Weak};
   5use std::time::{Duration, Instant};
   6
   7use calloop::generic::{FdWrapper, Generic};
   8use calloop::{EventLoop, LoopHandle, RegistrationToken};
   9
  10use collections::HashMap;
  11use copypasta::x11_clipboard::{Clipboard, Primary, X11ClipboardContext};
  12use copypasta::ClipboardProvider;
  13
  14use util::ResultExt;
  15use x11rb::connection::{Connection, RequestConnection};
  16use x11rb::cursor;
  17use x11rb::errors::ConnectionError;
  18use x11rb::protocol::randr::ConnectionExt as _;
  19use x11rb::protocol::xinput::ConnectionExt;
  20use x11rb::protocol::xkb::ConnectionExt as _;
  21use x11rb::protocol::xproto::{ChangeWindowAttributesAux, ConnectionExt as _};
  22use x11rb::protocol::{randr, render, xinput, xkb, xproto, Event};
  23use x11rb::resource_manager::Database;
  24use x11rb::xcb_ffi::XCBConnection;
  25use xim::{x11rb::X11rbClient, Client};
  26use xim::{AttributeName, InputStyle};
  27use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
  28use xkbcommon::xkb as xkbc;
  29
  30use crate::platform::linux::LinuxClient;
  31use crate::platform::{LinuxCommon, PlatformWindow};
  32use crate::{
  33    modifiers_from_xinput_info, point, px, AnyWindowHandle, Bounds, CursorStyle, DisplayId,
  34    Keystroke, Modifiers, ModifiersChangedEvent, Pixels, PlatformDisplay, PlatformInput, Point,
  35    ScrollDelta, Size, TouchPhase, WindowParams, X11Window,
  36};
  37
  38use super::{
  39    super::{open_uri_internal, SCROLL_LINES},
  40    X11Display, X11WindowStatePtr, XcbAtoms,
  41};
  42use super::{button_of_key, modifiers_from_state, pressed_button_from_mask};
  43use super::{XimCallbackEvent, XimHandler};
  44use crate::platform::linux::is_within_click_distance;
  45use crate::platform::linux::platform::DOUBLE_CLICK_INTERVAL;
  46use crate::platform::linux::xdg_desktop_portal::{Event as XDPEvent, XDPEventSource};
  47
  48pub(super) const XINPUT_MASTER_DEVICE: u16 = 1;
  49
  50pub(crate) struct WindowRef {
  51    window: X11WindowStatePtr,
  52    refresh_event_token: RegistrationToken,
  53}
  54
  55impl WindowRef {
  56    pub fn handle(&self) -> AnyWindowHandle {
  57        self.window.state.borrow().handle
  58    }
  59}
  60
  61impl Deref for WindowRef {
  62    type Target = X11WindowStatePtr;
  63
  64    fn deref(&self) -> &Self::Target {
  65        &self.window
  66    }
  67}
  68
  69#[derive(Debug)]
  70#[non_exhaustive]
  71pub enum EventHandlerError {
  72    XCBConnectionError(ConnectionError),
  73    XIMClientError(xim::ClientError),
  74}
  75
  76impl std::error::Error for EventHandlerError {}
  77
  78impl std::fmt::Display for EventHandlerError {
  79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  80        match self {
  81            EventHandlerError::XCBConnectionError(err) => err.fmt(f),
  82            EventHandlerError::XIMClientError(err) => err.fmt(f),
  83        }
  84    }
  85}
  86
  87impl From<ConnectionError> for EventHandlerError {
  88    fn from(err: ConnectionError) -> Self {
  89        EventHandlerError::XCBConnectionError(err)
  90    }
  91}
  92
  93impl From<xim::ClientError> for EventHandlerError {
  94    fn from(err: xim::ClientError) -> Self {
  95        EventHandlerError::XIMClientError(err)
  96    }
  97}
  98
  99pub struct X11ClientState {
 100    pub(crate) loop_handle: LoopHandle<'static, X11Client>,
 101    pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
 102
 103    pub(crate) last_click: Instant,
 104    pub(crate) last_location: Point<Pixels>,
 105    pub(crate) current_count: usize,
 106
 107    pub(crate) scale_factor: f32,
 108
 109    pub(crate) xcb_connection: Rc<XCBConnection>,
 110    pub(crate) x_root_index: usize,
 111    pub(crate) _resource_database: Database,
 112    pub(crate) atoms: XcbAtoms,
 113    pub(crate) windows: HashMap<xproto::Window, WindowRef>,
 114    pub(crate) focused_window: Option<xproto::Window>,
 115    pub(crate) xkb: xkbc::State,
 116    pub(crate) ximc: Option<X11rbClient<Rc<XCBConnection>>>,
 117    pub(crate) xim_handler: Option<XimHandler>,
 118    pub modifiers: Modifiers,
 119
 120    pub(crate) compose_state: xkbc::compose::State,
 121    pub(crate) pre_edit_text: Option<String>,
 122    pub(crate) composing: bool,
 123    pub(crate) cursor_handle: cursor::Handle,
 124    pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
 125    pub(crate) cursor_cache: HashMap<CursorStyle, xproto::Cursor>,
 126
 127    pub(crate) scroll_class_data: Vec<xinput::DeviceClassDataScroll>,
 128    pub(crate) scroll_x: Option<f32>,
 129    pub(crate) scroll_y: Option<f32>,
 130
 131    pub(crate) common: LinuxCommon,
 132    pub(crate) clipboard: X11ClipboardContext<Clipboard>,
 133    pub(crate) primary: X11ClipboardContext<Primary>,
 134}
 135
 136#[derive(Clone)]
 137pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
 138
 139impl X11ClientStatePtr {
 140    pub fn drop_window(&self, x_window: u32) {
 141        let client = X11Client(self.0.upgrade().expect("client already dropped"));
 142        let mut state = client.0.borrow_mut();
 143
 144        if let Some(window_ref) = state.windows.remove(&x_window) {
 145            state.loop_handle.remove(window_ref.refresh_event_token);
 146        }
 147
 148        state.cursor_styles.remove(&x_window);
 149
 150        if state.windows.is_empty() {
 151            state.common.signal.stop();
 152        }
 153    }
 154}
 155
 156#[derive(Clone)]
 157pub(crate) struct X11Client(Rc<RefCell<X11ClientState>>);
 158
 159impl X11Client {
 160    pub(crate) fn new() -> Self {
 161        let event_loop = EventLoop::try_new().unwrap();
 162
 163        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 164
 165        let handle = event_loop.handle();
 166
 167        handle
 168            .insert_source(main_receiver, {
 169                let handle = handle.clone();
 170                move |event, _, _: &mut X11Client| {
 171                    if let calloop::channel::Event::Msg(runnable) = event {
 172                        // Insert the runnables as idle callbacks, so we make sure that user-input and X11
 173                        // events have higher priority and runnables are only worked off after the event
 174                        // callbacks.
 175                        handle.insert_idle(|_| {
 176                            runnable.run();
 177                        });
 178                    }
 179                }
 180            })
 181            .unwrap();
 182
 183        let (xcb_connection, x_root_index) = XCBConnection::connect(None).unwrap();
 184        xcb_connection
 185            .prefetch_extension_information(xkb::X11_EXTENSION_NAME)
 186            .unwrap();
 187        xcb_connection
 188            .prefetch_extension_information(randr::X11_EXTENSION_NAME)
 189            .unwrap();
 190        xcb_connection
 191            .prefetch_extension_information(render::X11_EXTENSION_NAME)
 192            .unwrap();
 193        xcb_connection
 194            .prefetch_extension_information(xinput::X11_EXTENSION_NAME)
 195            .unwrap();
 196
 197        let xinput_version = xcb_connection
 198            .xinput_xi_query_version(2, 0)
 199            .unwrap()
 200            .reply()
 201            .unwrap();
 202        assert!(
 203            xinput_version.major_version >= 2,
 204            "XInput Extension v2 not supported."
 205        );
 206
 207        let master_device_query = xcb_connection
 208            .xinput_xi_query_device(XINPUT_MASTER_DEVICE)
 209            .unwrap()
 210            .reply()
 211            .unwrap();
 212        let scroll_class_data = master_device_query
 213            .infos
 214            .iter()
 215            .find(|info| info.type_ == xinput::DeviceType::MASTER_POINTER)
 216            .unwrap()
 217            .classes
 218            .iter()
 219            .filter_map(|class| class.data.as_scroll())
 220            .map(|class| *class)
 221            .collect::<Vec<_>>();
 222
 223        let atoms = XcbAtoms::new(&xcb_connection).unwrap();
 224        let xkb = xcb_connection
 225            .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION)
 226            .unwrap();
 227
 228        let atoms = atoms.reply().unwrap();
 229        let xkb = xkb.reply().unwrap();
 230        let events = xkb::EventType::STATE_NOTIFY;
 231        xcb_connection
 232            .xkb_select_events(
 233                xkb::ID::USE_CORE_KBD.into(),
 234                0u8.into(),
 235                events,
 236                0u8.into(),
 237                0u8.into(),
 238                &xkb::SelectEventsAux::new(),
 239            )
 240            .unwrap();
 241        assert!(xkb.supported);
 242
 243        let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
 244        let xkb_state = {
 245            let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
 246            let xkb_keymap = xkbc::x11::keymap_new_from_device(
 247                &xkb_context,
 248                &xcb_connection,
 249                xkb_device_id,
 250                xkbc::KEYMAP_COMPILE_NO_FLAGS,
 251            );
 252            xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
 253        };
 254        let compose_state = {
 255            let locale = std::env::var_os("LC_CTYPE").unwrap_or(OsString::from("C"));
 256            let table = xkbc::compose::Table::new_from_locale(
 257                &xkb_context,
 258                &locale,
 259                xkbc::compose::COMPILE_NO_FLAGS,
 260            )
 261            .log_err()
 262            .unwrap();
 263            xkbc::compose::State::new(&table, xkbc::compose::STATE_NO_FLAGS)
 264        };
 265
 266        let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection).unwrap();
 267
 268        let scale_factor = resource_database
 269            .get_value("Xft.dpi", "Xft.dpi")
 270            .ok()
 271            .flatten()
 272            .map(|dpi: f32| dpi / 96.0)
 273            .unwrap_or(1.0);
 274
 275        let cursor_handle = cursor::Handle::new(&xcb_connection, x_root_index, &resource_database)
 276            .unwrap()
 277            .reply()
 278            .unwrap();
 279
 280        let clipboard = X11ClipboardContext::<Clipboard>::new().unwrap();
 281        let primary = X11ClipboardContext::<Primary>::new().unwrap();
 282
 283        let xcb_connection = Rc::new(xcb_connection);
 284
 285        let ximc = X11rbClient::init(Rc::clone(&xcb_connection), x_root_index, None).ok();
 286        let xim_handler = if ximc.is_some() {
 287            Some(XimHandler::new())
 288        } else {
 289            None
 290        };
 291
 292        // Safety: Safe if xcb::Connection always returns a valid fd
 293        let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
 294
 295        handle
 296            .insert_source(
 297                Generic::new_with_error::<EventHandlerError>(
 298                    fd,
 299                    calloop::Interest::READ,
 300                    calloop::Mode::Level,
 301                ),
 302                {
 303                    let xcb_connection = xcb_connection.clone();
 304                    move |_readiness, _, client| {
 305                        while let Some(event) = xcb_connection.poll_for_event()? {
 306                            let mut state = client.0.borrow_mut();
 307                            if state.ximc.is_none() || state.xim_handler.is_none() {
 308                                drop(state);
 309                                client.handle_event(event);
 310                                continue;
 311                            }
 312
 313                            let mut ximc = state.ximc.take().unwrap();
 314                            let mut xim_handler = state.xim_handler.take().unwrap();
 315                            let xim_connected = xim_handler.connected;
 316                            drop(state);
 317
 318                            let xim_filtered = match ximc.filter_event(&event, &mut xim_handler) {
 319                                Ok(handled) => handled,
 320                                Err(err) => {
 321                                    log::error!("XIMClientError: {}", err);
 322                                    false
 323                                }
 324                            };
 325                            let xim_callback_event = xim_handler.last_callback_event.take();
 326
 327                            let mut state = client.0.borrow_mut();
 328                            state.ximc = Some(ximc);
 329                            state.xim_handler = Some(xim_handler);
 330                            drop(state);
 331
 332                            if let Some(event) = xim_callback_event {
 333                                client.handle_xim_callback_event(event);
 334                            }
 335
 336                            if xim_filtered {
 337                                continue;
 338                            }
 339
 340                            if xim_connected {
 341                                client.xim_handle_event(event);
 342                            } else {
 343                                client.handle_event(event);
 344                            }
 345                        }
 346
 347                        Ok(calloop::PostAction::Continue)
 348                    }
 349                },
 350            )
 351            .expect("Failed to initialize x11 event source");
 352
 353        handle
 354            .insert_source(XDPEventSource::new(&common.background_executor), {
 355                move |event, _, client| match event {
 356                    XDPEvent::WindowAppearance(appearance) => {
 357                        client.with_common(|common| common.appearance = appearance);
 358                        for (_, window) in &mut client.0.borrow_mut().windows {
 359                            window.window.set_appearance(appearance);
 360                        }
 361                    }
 362                }
 363            })
 364            .unwrap();
 365
 366        X11Client(Rc::new(RefCell::new(X11ClientState {
 367            modifiers: Modifiers::default(),
 368            event_loop: Some(event_loop),
 369            loop_handle: handle,
 370            common,
 371            last_click: Instant::now(),
 372            last_location: Point::new(px(0.0), px(0.0)),
 373            current_count: 0,
 374            scale_factor,
 375
 376            xcb_connection,
 377            x_root_index,
 378            _resource_database: resource_database,
 379            atoms,
 380            windows: HashMap::default(),
 381            focused_window: None,
 382            xkb: xkb_state,
 383            ximc,
 384            xim_handler,
 385
 386            compose_state: compose_state,
 387            pre_edit_text: None,
 388            composing: false,
 389
 390            cursor_handle,
 391            cursor_styles: HashMap::default(),
 392            cursor_cache: HashMap::default(),
 393
 394            scroll_class_data,
 395            scroll_x: None,
 396            scroll_y: None,
 397
 398            clipboard,
 399            primary,
 400        })))
 401    }
 402
 403    pub fn enable_ime(&self) {
 404        let mut state = self.0.borrow_mut();
 405        if state.ximc.is_none() {
 406            return;
 407        }
 408
 409        let mut ximc = state.ximc.take().unwrap();
 410        let mut xim_handler = state.xim_handler.take().unwrap();
 411        let mut ic_attributes = ximc
 412            .build_ic_attributes()
 413            .push(
 414                AttributeName::InputStyle,
 415                InputStyle::PREEDIT_CALLBACKS
 416                    | InputStyle::STATUS_NOTHING
 417                    | InputStyle::PREEDIT_NONE,
 418            )
 419            .push(AttributeName::ClientWindow, xim_handler.window)
 420            .push(AttributeName::FocusWindow, xim_handler.window);
 421
 422        let window_id = state.focused_window;
 423        drop(state);
 424        if let Some(window_id) = window_id {
 425            let window = self.get_window(window_id).unwrap();
 426            if let Some(area) = window.get_ime_area() {
 427                ic_attributes =
 428                    ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
 429                        b.push(
 430                            xim::AttributeName::SpotLocation,
 431                            xim::Point {
 432                                x: u32::from(area.origin.x + area.size.width) as i16,
 433                                y: u32::from(area.origin.y + area.size.height) as i16,
 434                            },
 435                        );
 436                    });
 437            }
 438        }
 439        ximc.create_ic(xim_handler.im_id, ic_attributes.build())
 440            .ok();
 441        state = self.0.borrow_mut();
 442        state.xim_handler = Some(xim_handler);
 443        state.ximc = Some(ximc);
 444    }
 445
 446    pub fn disable_ime(&self) {
 447        let mut state = self.0.borrow_mut();
 448        state.composing = false;
 449        if let Some(mut ximc) = state.ximc.take() {
 450            let xim_handler = state.xim_handler.as_ref().unwrap();
 451            ximc.destroy_ic(xim_handler.im_id, xim_handler.ic_id).ok();
 452            state.ximc = Some(ximc);
 453        }
 454    }
 455
 456    fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
 457        let state = self.0.borrow();
 458        state
 459            .windows
 460            .get(&win)
 461            .map(|window_reference| window_reference.window.clone())
 462    }
 463
 464    fn handle_event(&self, event: Event) -> Option<()> {
 465        match event {
 466            Event::ClientMessage(event) => {
 467                let window = self.get_window(event.window)?;
 468                let [atom, ..] = event.data.as_data32();
 469                let mut state = self.0.borrow_mut();
 470
 471                if atom == state.atoms.WM_DELETE_WINDOW {
 472                    // window "x" button clicked by user
 473                    if window.should_close() {
 474                        let window_ref = state.windows.remove(&event.window)?;
 475                        state.loop_handle.remove(window_ref.refresh_event_token);
 476                        // Rest of the close logic is handled in drop_window()
 477                    }
 478                }
 479            }
 480            Event::ConfigureNotify(event) => {
 481                let bounds = Bounds {
 482                    origin: Point {
 483                        x: event.x.into(),
 484                        y: event.y.into(),
 485                    },
 486                    size: Size {
 487                        width: event.width.into(),
 488                        height: event.height.into(),
 489                    },
 490                };
 491                let window = self.get_window(event.window)?;
 492                window.configure(bounds);
 493            }
 494            Event::Expose(event) => {
 495                let window = self.get_window(event.window)?;
 496                window.refresh();
 497            }
 498            Event::FocusIn(event) => {
 499                let window = self.get_window(event.event)?;
 500                window.set_focused(true);
 501                let mut state = self.0.borrow_mut();
 502                state.focused_window = Some(event.event);
 503                drop(state);
 504                self.enable_ime();
 505            }
 506            Event::FocusOut(event) => {
 507                let window = self.get_window(event.event)?;
 508                window.set_focused(false);
 509                let mut state = self.0.borrow_mut();
 510                state.focused_window = None;
 511                state.compose_state.reset();
 512                state.pre_edit_text.take();
 513                drop(state);
 514                self.disable_ime();
 515                window.handle_ime_delete();
 516            }
 517            Event::XkbStateNotify(event) => {
 518                let mut state = self.0.borrow_mut();
 519                state.xkb.update_mask(
 520                    event.base_mods.into(),
 521                    event.latched_mods.into(),
 522                    event.locked_mods.into(),
 523                    0,
 524                    0,
 525                    event.locked_group.into(),
 526                );
 527                let modifiers = Modifiers::from_xkb(&state.xkb);
 528                let focused_window_id = state.focused_window?;
 529                state.modifiers = modifiers;
 530                drop(state);
 531
 532                let focused_window = self.get_window(focused_window_id)?;
 533                focused_window.handle_input(PlatformInput::ModifiersChanged(
 534                    ModifiersChangedEvent { modifiers },
 535                ));
 536            }
 537            Event::KeyPress(event) => {
 538                let window = self.get_window(event.event)?;
 539                let mut state = self.0.borrow_mut();
 540
 541                let modifiers = modifiers_from_state(event.state);
 542                state.modifiers = modifiers;
 543
 544                let keystroke = {
 545                    let code = event.detail.into();
 546                    let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 547                    state.xkb.update_key(code, xkbc::KeyDirection::Down);
 548                    let keysym = state.xkb.key_get_one_sym(code);
 549                    if keysym.is_modifier_key() {
 550                        return Some(());
 551                    }
 552                    state.compose_state.feed(keysym);
 553                    match state.compose_state.status() {
 554                        xkbc::Status::Composed => {
 555                            state.pre_edit_text.take();
 556                            keystroke.ime_key = state.compose_state.utf8();
 557                            keystroke.key =
 558                                xkbc::keysym_get_name(state.compose_state.keysym().unwrap());
 559                        }
 560                        xkbc::Status::Composing => {
 561                            state.pre_edit_text = state
 562                                .compose_state
 563                                .utf8()
 564                                .or(crate::Keystroke::underlying_dead_key(keysym));
 565                            let pre_edit = state.pre_edit_text.clone().unwrap_or(String::default());
 566                            drop(state);
 567                            window.handle_ime_preedit(pre_edit);
 568                            state = self.0.borrow_mut();
 569                        }
 570                        xkbc::Status::Cancelled => {
 571                            let pre_edit = state.pre_edit_text.take();
 572                            drop(state);
 573                            if let Some(pre_edit) = pre_edit {
 574                                window.handle_ime_commit(pre_edit);
 575                            }
 576                            if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
 577                                window.handle_ime_preedit(current_key);
 578                            }
 579                            state = self.0.borrow_mut();
 580                            state.compose_state.feed(keysym);
 581                        }
 582                        _ => {}
 583                    }
 584                    keystroke
 585                };
 586                drop(state);
 587                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
 588                    keystroke,
 589                    is_held: false,
 590                }));
 591            }
 592            Event::KeyRelease(event) => {
 593                let window = self.get_window(event.event)?;
 594                let mut state = self.0.borrow_mut();
 595
 596                let modifiers = modifiers_from_state(event.state);
 597                state.modifiers = modifiers;
 598
 599                let keystroke = {
 600                    let code = event.detail.into();
 601                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 602                    state.xkb.update_key(code, xkbc::KeyDirection::Up);
 603                    let keysym = state.xkb.key_get_one_sym(code);
 604                    if keysym.is_modifier_key() {
 605                        return Some(());
 606                    }
 607                    keystroke
 608                };
 609                drop(state);
 610                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
 611            }
 612            Event::XinputButtonPress(event) => {
 613                let window = self.get_window(event.event)?;
 614                let mut state = self.0.borrow_mut();
 615
 616                let modifiers = modifiers_from_xinput_info(event.mods);
 617                state.modifiers = modifiers;
 618
 619                let position = point(
 620                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 621                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 622                );
 623
 624                if state.composing && state.ximc.is_some() {
 625                    drop(state);
 626                    self.disable_ime();
 627                    self.enable_ime();
 628                    window.handle_ime_unmark();
 629                    state = self.0.borrow_mut();
 630                } else if let Some(text) = state.pre_edit_text.take() {
 631                    state.compose_state.reset();
 632                    drop(state);
 633                    window.handle_ime_commit(text);
 634                    state = self.0.borrow_mut();
 635                }
 636                if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
 637                    let click_elapsed = state.last_click.elapsed();
 638
 639                    if click_elapsed < DOUBLE_CLICK_INTERVAL
 640                        && is_within_click_distance(state.last_location, position)
 641                    {
 642                        state.current_count += 1;
 643                    } else {
 644                        state.current_count = 1;
 645                    }
 646
 647                    state.last_click = Instant::now();
 648                    state.last_location = position;
 649                    let current_count = state.current_count;
 650
 651                    drop(state);
 652                    window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
 653                        button,
 654                        position,
 655                        modifiers,
 656                        click_count: current_count,
 657                        first_mouse: false,
 658                    }));
 659                } else {
 660                    log::warn!("Unknown button press: {event:?}");
 661                }
 662            }
 663            Event::XinputButtonRelease(event) => {
 664                let window = self.get_window(event.event)?;
 665                let mut state = self.0.borrow_mut();
 666                let modifiers = modifiers_from_xinput_info(event.mods);
 667                state.modifiers = modifiers;
 668
 669                let position = point(
 670                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 671                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 672                );
 673                if let Some(button) = button_of_key(event.detail.try_into().unwrap()) {
 674                    let click_count = state.current_count;
 675                    drop(state);
 676                    window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
 677                        button,
 678                        position,
 679                        modifiers,
 680                        click_count,
 681                    }));
 682                }
 683            }
 684            Event::XinputMotion(event) => {
 685                let window = self.get_window(event.event)?;
 686                let mut state = self.0.borrow_mut();
 687                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
 688                let position = point(
 689                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 690                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 691                );
 692                let modifiers = modifiers_from_xinput_info(event.mods);
 693                state.modifiers = modifiers;
 694                drop(state);
 695
 696                let axisvalues = event
 697                    .axisvalues
 698                    .iter()
 699                    .map(|axisvalue| fp3232_to_f32(*axisvalue))
 700                    .collect::<Vec<_>>();
 701
 702                if event.valuator_mask[0] & 3 != 0 {
 703                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
 704                        position,
 705                        pressed_button,
 706                        modifiers,
 707                    }));
 708                }
 709
 710                let mut valuator_idx = 0;
 711                let scroll_class_data = self.0.borrow().scroll_class_data.clone();
 712                for shift in 0..32 {
 713                    if (event.valuator_mask[0] >> shift) & 1 == 0 {
 714                        continue;
 715                    }
 716
 717                    for scroll_class in &scroll_class_data {
 718                        if scroll_class.scroll_type == xinput::ScrollType::HORIZONTAL
 719                            && scroll_class.number == shift
 720                        {
 721                            let new_scroll = axisvalues[valuator_idx]
 722                                / fp3232_to_f32(scroll_class.increment)
 723                                * SCROLL_LINES as f32;
 724                            let old_scroll = self.0.borrow().scroll_x;
 725                            self.0.borrow_mut().scroll_x = Some(new_scroll);
 726
 727                            if let Some(old_scroll) = old_scroll {
 728                                let delta_scroll = old_scroll - new_scroll;
 729                                window.handle_input(PlatformInput::ScrollWheel(
 730                                    crate::ScrollWheelEvent {
 731                                        position,
 732                                        delta: ScrollDelta::Lines(Point::new(delta_scroll, 0.0)),
 733                                        modifiers,
 734                                        touch_phase: TouchPhase::default(),
 735                                    },
 736                                ));
 737                            }
 738                        } else if scroll_class.scroll_type == xinput::ScrollType::VERTICAL
 739                            && scroll_class.number == shift
 740                        {
 741                            // the `increment` is the valuator delta equivalent to one positive unit of scrolling. Here that means SCROLL_LINES lines.
 742                            let new_scroll = axisvalues[valuator_idx]
 743                                / fp3232_to_f32(scroll_class.increment)
 744                                * SCROLL_LINES as f32;
 745                            let old_scroll = self.0.borrow().scroll_y;
 746                            self.0.borrow_mut().scroll_y = Some(new_scroll);
 747
 748                            if let Some(old_scroll) = old_scroll {
 749                                let delta_scroll = old_scroll - new_scroll;
 750                                window.handle_input(PlatformInput::ScrollWheel(
 751                                    crate::ScrollWheelEvent {
 752                                        position,
 753                                        delta: ScrollDelta::Lines(Point::new(0.0, delta_scroll)),
 754                                        modifiers,
 755                                        touch_phase: TouchPhase::default(),
 756                                    },
 757                                ));
 758                            }
 759                        }
 760                    }
 761
 762                    valuator_idx += 1;
 763                }
 764            }
 765            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
 766                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)
 767                self.0.borrow_mut().scroll_y = None;
 768
 769                let window = self.get_window(event.event)?;
 770                let mut state = self.0.borrow_mut();
 771                let pressed_button = pressed_button_from_mask(event.buttons[0]);
 772                let position = point(
 773                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 774                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 775                );
 776                let modifiers = modifiers_from_xinput_info(event.mods);
 777                state.modifiers = modifiers;
 778                drop(state);
 779
 780                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
 781                    pressed_button,
 782                    position,
 783                    modifiers,
 784                }));
 785            }
 786            _ => {}
 787        };
 788
 789        Some(())
 790    }
 791
 792    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
 793        match event {
 794            XimCallbackEvent::XimXEvent(event) => {
 795                self.handle_event(event);
 796            }
 797            XimCallbackEvent::XimCommitEvent(window, text) => {
 798                self.xim_handle_commit(window, text);
 799            }
 800            XimCallbackEvent::XimPreeditEvent(window, text) => {
 801                self.xim_handle_preedit(window, text);
 802            }
 803        };
 804    }
 805
 806    fn xim_handle_event(&self, event: Event) -> Option<()> {
 807        match event {
 808            Event::KeyPress(event) | Event::KeyRelease(event) => {
 809                let mut state = self.0.borrow_mut();
 810                let mut ximc = state.ximc.take().unwrap();
 811                let mut xim_handler = state.xim_handler.take().unwrap();
 812                drop(state);
 813                xim_handler.window = event.event;
 814                ximc.forward_event(
 815                    xim_handler.im_id,
 816                    xim_handler.ic_id,
 817                    xim::ForwardEventFlag::empty(),
 818                    &event,
 819                )
 820                .unwrap();
 821                let mut state = self.0.borrow_mut();
 822                state.ximc = Some(ximc);
 823                state.xim_handler = Some(xim_handler);
 824                drop(state);
 825            }
 826            event => {
 827                self.handle_event(event);
 828            }
 829        }
 830        Some(())
 831    }
 832
 833    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
 834        let window = self.get_window(window).unwrap();
 835        let mut state = self.0.borrow_mut();
 836        state.composing = false;
 837        drop(state);
 838
 839        window.handle_ime_commit(text);
 840        Some(())
 841    }
 842
 843    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
 844        let window = self.get_window(window).unwrap();
 845        window.handle_ime_preedit(text);
 846
 847        let mut state = self.0.borrow_mut();
 848        let mut ximc = state.ximc.take().unwrap();
 849        let mut xim_handler = state.xim_handler.take().unwrap();
 850        state.composing = true;
 851        drop(state);
 852
 853        if let Some(area) = window.get_ime_area() {
 854            let ic_attributes = ximc
 855                .build_ic_attributes()
 856                .push(
 857                    xim::AttributeName::InputStyle,
 858                    xim::InputStyle::PREEDIT_CALLBACKS
 859                        | xim::InputStyle::STATUS_NOTHING
 860                        | xim::InputStyle::PREEDIT_POSITION,
 861                )
 862                .push(xim::AttributeName::ClientWindow, xim_handler.window)
 863                .push(xim::AttributeName::FocusWindow, xim_handler.window)
 864                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
 865                    b.push(
 866                        xim::AttributeName::SpotLocation,
 867                        xim::Point {
 868                            x: u32::from(area.origin.x + area.size.width) as i16,
 869                            y: u32::from(area.origin.y + area.size.height) as i16,
 870                        },
 871                    );
 872                })
 873                .build();
 874            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
 875                .ok();
 876        }
 877        let mut state = self.0.borrow_mut();
 878        state.ximc = Some(ximc);
 879        state.xim_handler = Some(xim_handler);
 880        drop(state);
 881        Some(())
 882    }
 883}
 884
 885impl LinuxClient for X11Client {
 886    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
 887        f(&mut self.0.borrow_mut().common)
 888    }
 889
 890    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 891        let state = self.0.borrow();
 892        let setup = state.xcb_connection.setup();
 893        setup
 894            .roots
 895            .iter()
 896            .enumerate()
 897            .filter_map(|(root_id, _)| {
 898                Some(Rc::new(X11Display::new(&state.xcb_connection, root_id)?)
 899                    as Rc<dyn PlatformDisplay>)
 900            })
 901            .collect()
 902    }
 903
 904    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 905        let state = self.0.borrow();
 906
 907        Some(Rc::new(
 908            X11Display::new(&state.xcb_connection, state.x_root_index)
 909                .expect("There should always be a root index"),
 910        ))
 911    }
 912
 913    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 914        let state = self.0.borrow();
 915
 916        Some(Rc::new(X11Display::new(
 917            &state.xcb_connection,
 918            id.0 as usize,
 919        )?))
 920    }
 921
 922    fn open_window(
 923        &self,
 924        handle: AnyWindowHandle,
 925        params: WindowParams,
 926    ) -> Box<dyn PlatformWindow> {
 927        let mut state = self.0.borrow_mut();
 928        let x_window = state.xcb_connection.generate_id().unwrap();
 929
 930        let window = X11Window::new(
 931            handle,
 932            X11ClientStatePtr(Rc::downgrade(&self.0)),
 933            state.common.foreground_executor.clone(),
 934            params,
 935            &state.xcb_connection,
 936            state.x_root_index,
 937            x_window,
 938            &state.atoms,
 939            state.scale_factor,
 940            state.common.appearance,
 941        );
 942
 943        let screen_resources = state
 944            .xcb_connection
 945            .randr_get_screen_resources(x_window)
 946            .unwrap()
 947            .reply()
 948            .expect("Could not find available screens");
 949
 950        let mode = screen_resources
 951            .crtcs
 952            .iter()
 953            .find_map(|crtc| {
 954                let crtc_info = state
 955                    .xcb_connection
 956                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
 957                    .ok()?
 958                    .reply()
 959                    .ok()?;
 960
 961                screen_resources
 962                    .modes
 963                    .iter()
 964                    .find(|m| m.id == crtc_info.mode)
 965            })
 966            .expect("Unable to find screen refresh rate");
 967
 968        let refresh_event_token = state
 969            .loop_handle
 970            .insert_source(calloop::timer::Timer::immediate(), {
 971                let refresh_duration = mode_refresh_rate(mode);
 972                move |mut instant, (), client| {
 973                    let state = client.0.borrow_mut();
 974                    state
 975                        .xcb_connection
 976                        .send_event(
 977                            false,
 978                            x_window,
 979                            xproto::EventMask::EXPOSURE,
 980                            xproto::ExposeEvent {
 981                                response_type: xproto::EXPOSE_EVENT,
 982                                sequence: 0,
 983                                window: x_window,
 984                                x: 0,
 985                                y: 0,
 986                                width: 0,
 987                                height: 0,
 988                                count: 1,
 989                            },
 990                        )
 991                        .unwrap();
 992                    let _ = state.xcb_connection.flush().unwrap();
 993                    // Take into account that some frames have been skipped
 994                    let now = Instant::now();
 995                    while instant < now {
 996                        instant += refresh_duration;
 997                    }
 998                    calloop::timer::TimeoutAction::ToInstant(instant)
 999                }
1000            })
1001            .expect("Failed to initialize refresh timer");
1002
1003        let window_ref = WindowRef {
1004            window: window.0.clone(),
1005            refresh_event_token,
1006        };
1007
1008        state.windows.insert(x_window, window_ref);
1009        Box::new(window)
1010    }
1011
1012    fn set_cursor_style(&self, style: CursorStyle) {
1013        let mut state = self.0.borrow_mut();
1014        let Some(focused_window) = state.focused_window else {
1015            return;
1016        };
1017        let current_style = state
1018            .cursor_styles
1019            .get(&focused_window)
1020            .unwrap_or(&CursorStyle::Arrow);
1021        if *current_style == style {
1022            return;
1023        }
1024
1025        let cursor = match state.cursor_cache.get(&style) {
1026            Some(cursor) => *cursor,
1027            None => {
1028                let cursor = state
1029                    .cursor_handle
1030                    .load_cursor(&state.xcb_connection, &style.to_icon_name())
1031                    .expect("failed to load cursor");
1032                state.cursor_cache.insert(style, cursor);
1033                cursor
1034            }
1035        };
1036
1037        state.cursor_styles.insert(focused_window, style);
1038        state
1039            .xcb_connection
1040            .change_window_attributes(
1041                focused_window,
1042                &ChangeWindowAttributesAux {
1043                    cursor: Some(cursor),
1044                    ..Default::default()
1045                },
1046            )
1047            .expect("failed to change window cursor");
1048    }
1049
1050    fn open_uri(&self, uri: &str) {
1051        open_uri_internal(uri, None);
1052    }
1053
1054    fn write_to_primary(&self, item: crate::ClipboardItem) {
1055        self.0.borrow_mut().primary.set_contents(item.text).ok();
1056    }
1057
1058    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1059        self.0.borrow_mut().clipboard.set_contents(item.text).ok();
1060    }
1061
1062    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1063        self.0
1064            .borrow_mut()
1065            .primary
1066            .get_contents()
1067            .ok()
1068            .map(|text| crate::ClipboardItem {
1069                text,
1070                metadata: None,
1071            })
1072    }
1073
1074    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1075        self.0
1076            .borrow_mut()
1077            .clipboard
1078            .get_contents()
1079            .ok()
1080            .map(|text| crate::ClipboardItem {
1081                text,
1082                metadata: None,
1083            })
1084    }
1085
1086    fn run(&self) {
1087        let mut event_loop = self
1088            .0
1089            .borrow_mut()
1090            .event_loop
1091            .take()
1092            .expect("App is already running");
1093
1094        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1095    }
1096
1097    fn active_window(&self) -> Option<AnyWindowHandle> {
1098        let state = self.0.borrow();
1099        state.focused_window.and_then(|focused_window| {
1100            state
1101                .windows
1102                .get(&focused_window)
1103                .map(|window| window.handle())
1104        })
1105    }
1106}
1107
1108// Adatpted from:
1109// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1110pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1111    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1112    let micros = 1_000_000_000 / millihertz;
1113    log::info!("Refreshing at {} micros", micros);
1114    Duration::from_micros(micros)
1115}
1116
1117fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1118    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1119}