client.rs

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